Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to catch and process null arguments?

When I code, I often ask myself the same question :

Do I have to verify all arguments are not null ? So, in each method, I will have something like that :

if (arg1 == null) 
{
    throw FooException("...");
}

if (arg2 == null) 
{
    throw FooException("...");
}

If not, in which case is preferable ?

What's the best practices ?

like image 943
Sandro Munda Avatar asked Apr 14 '26 02:04

Sandro Munda


2 Answers

As always, it depends.

If you're writing an API to be used by other teams / organizations, such defensive programming with precondition checks on public functions can really help your users; when using an external library, a meaningful error message like 'argument passed to foo() should not be null' is way better than NullPointerException thrown from some inner class.

Outside of API, though, I think such checks clutter the code too much. Thrown NullPointerExceptions are usually pretty easy to trace with debugger anyway. In languages that support them, you can consider using assertions - their syntax is usually less cumbersome, and you can turn them off on production so the checks won't degrade performance.

like image 190
socha23 Avatar answered Apr 16 '26 11:04

socha23


Unfortunetly, yes. you should check all arguments. Now ideally, if you code with good design practices one function should not have more than 4 or 5 arguments, at the most.

Having said that, one should always check for null values in function entry and throw appropriate exception or IllegalArgumentException (my fav).

Furhter, one should never pass NULL to a function and should never return a NULL. Sounds simple but it will save lots of code and bugs. Have a look at the NULL Design Pattern too.

like image 37
Ravi Bhatt Avatar answered Apr 16 '26 10:04

Ravi Bhatt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!