Best practices: what should an "IsValid" boolean function return when passed a null argument?

2.1k views Asked by At

Given a bool validation function that takes an argument and returns true or false based on argument's compliance to some internal rules:

if the argument is null, should the function:

  • return false
  • return true
  • do neither and simply raise a ArgumentNullException

I would tend to believe the best practice is to raise the exception. I am however curious to hear others experience on the subject.

Given the sole choice of a bool, I am personally tempted to return false, but could see benefits in returning true also, based on the context of the function's usage. A null string for instance could be interpreted as empty and may be considered valid.

Are there best practice guidelines for this specific situation? I am looking for a guideline, like ones found in books like Code Complete.

Does it always need to be a case by case?

2

There are 2 answers

1
outlyer On BEST ANSWER

I don't think there's a general best practice, it will depend on the semantics.

Does it make sense to receive null? If so, return true or false based on what makes more sense, e.g. an hypothetical isAlphaNumericString(String) returning true when passed null is most likely nonsensical, but returning false may make sense.

But if it makes no sense to receive null, then a null marks a problem in the call, raise an exception to enforce the caller to make sense.

8
davidhigh On

As I interpret your question, your input-variable space is determined by each value the variable can take augmented by a null state. In SQL for example, this corresponds to some type, say INTEGER and NULL. In C++, for example, it corresponds to something like boost::optional<int> in which null means "uninitialized".

Now, I think the cleanest solution is to augment the result-space as well with null. This is also the choice both examples above follow (or at least commonly follow). For example, if a scalar function such as LENGTH() or also a comparison operator in SQL takes a NULL argument, it usually also returns NULL.

More on the theoretical side, this implements somthing like an isomorphism from the null-subspace in definition space to the null-subspace in result space (and the same holds for the complement, i.e. the non-null space). The advantage of this is tha you do not have to reinterpret your original function at all.