When writing a library function, such as

double getAvg(double[]);

how should one handle the empty array?

(Note that, mathematically speaking the avg of an empty set is undefined.)

  • 3
    Throw an exception, or return NaN. Up to you, just be consistent. Java typically throws (NoSuchElementException when asked for the maximum element of an empty collection for example). – Ordous Jul 21 '15 at 14:49

Whatever you do, document it. If users do not like the default behaviour you provide, they can then adapt your function to their needs.

Here are a couple of possibilities, sorted from best to least preferred (in my opinion).

  • There is no sensible value in these cases, so we need to return the absence of a value. This might be a double* or double? with a null pointer, or a Maybe Double type or a Optional<double> object, depending on your language. These techniques have the benefit of lifting the absence of a value to the type system, so you can enforce that the user checks for the error condition.

  • This is a logic error, so you should throw an exception, or use whatever mechanism is idiomatic in your language to specify an error. E.g. in Go, you would return multiple arguments with one being an error code, whereas you might set errno in C. If users would rather have a certain default value, they can then catch the exception.

  • Floating point numbers have a sane default value that could be returned in such cases. If users do not like the default value, they can explicitly check for the error-inducing input, and provide their own error behaviour.

    • the default should be 0, since this is generally the default for numbers.
    • the default should be NaN (= 0/0) to signal the absence of a value. If the language supports IEEE floating point operations, this will quickly “poison” all computations using that value. Note that NaN is a valid return value if any of the inputs was also NaN.
  • If 0 is a meaningful default value, then that is independent of the specific numeric type. Conversely, if semantically zero does not make sense as fallback, the IEEE float 0.0 is not a good value to return. – user7043 Jul 21 '15 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.