functionbooleanvalidationrulesdesign-guidelines

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


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:

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?


Solution

  • 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.