"special" return 表示条件的值如何调用?
How are "special" return values that signal a condition called?
假设我有一个计算长度的函数,return将其作为正整数,但也可以 return -1
超时,-2
"cannot compute",以及 -3
用于无效参数。
尽管对最佳实践、适当的例外等进行了任何讨论,但这在遗留代码库中经常发生。这种做法或超出正常输出值范围的 return 值的名称是什么,-1
是最常见的?
这是 "magic" value 的一个例子。当这个想法应用于函数的 return 值时,我不知道有任何更具体的术语。
Exceptions vs. status returns 文章将它们称为 return 状态代码:
Broadly speaking, there are two ways to handle errors as they pass
from layer to layer in software: throwing exceptions and returning
status codes...
With status returns, a valuable channel of communication (the return
value of the function) has been taken over for error handling.
我个人也将它们称为状态代码,类似于 HTTP 状态代码(如果我们假装 HTTP 响应就像一个函数 return)。
作为旁注,除了异常和 return 状态代码之外,还有一种 monadic 方法来处理错误,在某种意义上它结合了前两种方法.例如,在 Scala 中,Either
monad 可用于指定一个 return 值,该值可以同时表示错误状态代码和常规快乐值,而无需为状态代码屏蔽部分域:
def divide(a: Double, b: Double): Either[String, Double] =
if (b == 0.0) Left("Division by zero") else Right(a / b)
divide(4,0)
divide(4,2)
输出
res0: Either[String,Double] = Left(Division by zero)
res1: Either[String,Double] = Right(2.0)
假设我有一个计算长度的函数,return将其作为正整数,但也可以 return -1
超时,-2
"cannot compute",以及 -3
用于无效参数。
尽管对最佳实践、适当的例外等进行了任何讨论,但这在遗留代码库中经常发生。这种做法或超出正常输出值范围的 return 值的名称是什么,-1
是最常见的?
这是 "magic" value 的一个例子。当这个想法应用于函数的 return 值时,我不知道有任何更具体的术语。
Exceptions vs. status returns 文章将它们称为 return 状态代码:
Broadly speaking, there are two ways to handle errors as they pass from layer to layer in software: throwing exceptions and returning status codes... With status returns, a valuable channel of communication (the return value of the function) has been taken over for error handling.
我个人也将它们称为状态代码,类似于 HTTP 状态代码(如果我们假装 HTTP 响应就像一个函数 return)。
作为旁注,除了异常和 return 状态代码之外,还有一种 monadic 方法来处理错误,在某种意义上它结合了前两种方法.例如,在 Scala 中,Either
monad 可用于指定一个 return 值,该值可以同时表示错误状态代码和常规快乐值,而无需为状态代码屏蔽部分域:
def divide(a: Double, b: Double): Either[String, Double] =
if (b == 0.0) Left("Division by zero") else Right(a / b)
divide(4,0)
divide(4,2)
输出
res0: Either[String,Double] = Left(Division by zero)
res1: Either[String,Double] = Right(2.0)