1

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?

chadisbad
  • 23
  • 3

1 Answers1

1

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.

Sophie Swett
  • 1,349