I have to create a method

CalculateMean(int[] x)

If the input is an empty array, should I return 0 (or some number), or throw exception?

  • 1
    As a user of your API, what would you expect to happen in that case? There isn't exactly a right or wrong answer. Sep 12 '16 at 16:02
  • As a user, I get incorrect results if I return 1 or 0 for empty input
    – chadisbad
    Sep 12 '16 at 16:05
  • You need to decide if an empty array is valid input into your method. Does an empty input differ from null or should they be treated the same. Once you can answer these you're most of the way to deciding what to do.
    – Steve
    Sep 12 '16 at 16:24
  • In this case you should definitely not return 1 or 0 for empty input. That makes absolutely no sense as 1 and 0 could be valid return values.
    – Steve
    Sep 12 '16 at 16:25
  • Given that the question appears to be about computing the arithmetic mean with zero length input (which is a divide by zero), the question appears be about how to handle invalid input, rather than whether it is worth dealing with valid edge or degenerate cases.
    – Erik Eidt
    Sep 12 '16 at 17:30

In my opinion, you should definitely throw an exception (unless the return type is nullable).

Since the empty array has no mean, there is no correct number that a CalculateMean method could return when called on the empty array. Returning any number would be incorrect.

Since returning any number would be incorrect, there are only two options that would be correct:

  • throw an exception, or
  • make the return type of CalculateMean nullable, and return null.

Whatever you do, make sure that the documentation for CalculateMean states exactly what it does when you pass it an empty array.


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