为什么函数总是返回相同的类型? [英] Why should functions always return the same type?

查看:112
本文介绍了为什么函数总是返回相同的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读到函数应该只返回一个类型
,所以下面的代码被认为是坏代码:

  def x(foo):
如果foo中的'bar':
return(foo,'bar')
return None

我想更好的解决方案是

$ p $ def x( foo):
如果foo中有'bar':
return(foo,'bar')
return()

如果返回一个None,那么创建一个新的空元组不是更便宜的内存方式吗?或者这个时间差别太小了,即使在大型项目中也没有注意到?

解决方案

为什么函数应该返回一致类型的值?符合以下两条规则。

规则1 - 函数具有类型 - 映射到输出的输入。它必须返回一致的结果类型,或者它不是一个函数。



在数学上,我们说某个函数F是从域D到范围R的映射。 F:D - > [R 。域和范围构成函数的类型。规则2 - 当你有一个问题的时候,输入类型和结果类型对于函数的定义是至关重要的。

或者无法返回正确的结果,引发异常。

  def x(foo):
if bar 'in foo:
return(foo,'bar')
raise Exception(哦,亲爱的我。)

You 可以打破以上规则,但长期可维护性和可理解性的成本是天文数字。

< 回归一个没有比这更便宜的记忆?错误的问题。



关键是不能以代价清晰,可读,明显的代码优化内存。


I read somewhere that functions should always return only one type so the following code is considered as bad code:

def x(foo):
 if 'bar' in foo:
  return (foo, 'bar')
 return None

I guess the better solution would be

def x(foo):
 if 'bar' in foo:
  return (foo, 'bar')
 return ()

Wouldn't it be cheaper memory wise to return a None then to create a new empty tuple or is this time difference too small to notice even in larger projects?

解决方案

Why should functions return values of a consistent type? To meet the following two rules.

Rule 1 -- a function has a "type" -- inputs mapped to outputs. It must return a consistent type of result, or it isn't a function. It's a mess.

Mathematically, we say some function, F, is a mapping from domain, D, to range, R. F: D -> R. The domain and range form the "type" of the function. The input types and the result type are as essential to the definition of the function as is the name or the body.

Rule 2 -- when you have a "problem" or can't return a proper result, raise an exception.

def x(foo):
    if 'bar' in foo:
        return (foo, 'bar')
     raise Exception( "oh, dear me." )

You can break the above rules, but the cost of long-term maintainability and comprehensibility is astronomical.

"Wouldn't it be cheaper memory wise to return a None?" Wrong question.

The point is not to optimize memory at the cost of clear, readable, obvious code.

这篇关于为什么函数总是返回相同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆