假设我有一个计算长度并将其作为正整数返回的函数,但也可以返回 -1
表示超时,-2
表示“无法计算”和 -3
表示无效参数。
尽管有关于最佳实践、适当异常(exception)等的讨论,但这种情况在遗留代码库中经常发生。这种做法或超出正常输出值范围的返回值(最常见的是 -1
)的名称是什么?
最佳答案
Exceptions vs. status returns文章将它们称为返回状态代码:
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 响应就像函数返回)。
顺便说一句,除了异常和返回状态代码之外,还存在一种monadic错误处理方法,它在某种意义上结合了前两种方法。例如,在 Scala 中,Either
monad 可用于指定一个返回值,该返回值既可以表示错误状态代码,也可以表示常规的快乐值,而无需屏蔽状态代码的部分域:
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)
关于error-handling - "special"返回值如何表示调用的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58340400/