When writing a library function, such as
how should one handle the empty array?
(Note that, mathematically speaking the avg of an empty set is undefined.)
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
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? 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.
0, since this is generally the default for numbers.