Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i explain that if (xyz == null) checks are not "protective"

i have a few developers who constantly put If null checks

For example:

Run(Order order)
{
  if (order == null) return;
}

in their code as they think they are protecting their class if someone passes in a parameter that is null. I am trying to tell them the flaw in their logic because if someone is passing in null in this case, its most likely an issue with the consumer code and instead of this class throwing an exception and failing fast, it gracefully handles the bad behavior of the consumer and keep chugging away.

another suggestion is to have precondition or guard class that fail fast and throw exceptions. any thing but ignoring that fact that the consumer probably has some other issue and i am help mask it.

how do i get folks to appreciate the fact that your class shouldn't be so forgiving. if someone doesn't pass in good data, they should be told.

any good articles or suggestions to help me get this point across?

like image 435
leora Avatar asked Nov 28 '22 15:11

leora


1 Answers

If your class cannot accept null arguments, then the best thing to do is this:

if (arg == null)
    throw new ArgumentNullException();

This is vastly preferable to getting a NullPointerException deeper down the stack. In the worst case scenario, you'll cache that null somewhere and won't actually trigger the exception until much later, and see how much fun you'll have debugging the problem then.

And as others have stated, sometimes the contract says that null is okay. In that case, having a guard clause around some parts of the code is correct--although even then I'd say that the best design would be to add an overload without the optionally-null arguments.

like image 90
JSBձոգչ Avatar answered Dec 15 '22 05:12

JSBձոգչ