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

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

问题描述

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

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

我想更好的解决方案是

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

返回一个 None 然后创建一个新的空元组是否会更节省内存,或者这个时间差异是否太小以至于即使在更大的项目中也无法注意到?

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.

规则 1——函数有一个类型"——输入映射到输出.它必须返回一致类型的结果,否则它不是一个函数.一团糟.

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.

在数学上,我们说某个函数 F 是从域 D 到范围 R 的映射.F: D ->R.域和范围构成了函数的类型".输入类型和结果类型对于函数的定义与名称或函数体一样重要.

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.

规则 2 -- 当您遇到问题"或无法返回正确结果时,引发异常.

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.

返回 None 不是更便宜的内存吗?"问错了.

"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天全站免登陆