How are "special" return values that signal a condition called?

Viewed 33

Suppose I have a function which calculates a length and returns it as a positive integer, but could also return -1 for timeout, -2 for "cannot compute", and -3 for invalid arguments.

Notwithstanding any discussion on best practices, proper exceptions, and whatnot, this occurs regularly in legacy codebases. What is the name for this practice or for return values which are outside of the normal output value range, -1 being the most common?

2 Answers

Exceptions vs. status returns article refers to them as return status codes:

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.

Personally I would also call them status codes, similarly to HTTP status codes (if we pretend HTTP response is like a function return).

As a side note, beside exceptions and return status codes, there also exists a monadic approach to error handling, which in some sense combines the former two approaches. For example, in Scala, Either monad may be used to specify a return value that can express both an error status code and a regular happy value without having to block out part of the domain for status codes:

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)

which outputs

res0: Either[String,Double] = Left(Division by zero)
res1: Either[String,Double] = Right(2.0)

That's an example of a "magic" value. I don't know of any more specific term for when this idea is applied to a function's return value.

Related