Tuesday, November 24, 2015

Get rid of null checks

As a developer we do our best to catch the null values and fail fast. I was writing too much code lines like below.

if (user == null) {
    throw new IllegalArgumentException("user most not be null.");
} 


After a while codebase can become dirty with this lines copy/pasted everywhere. While I was reading some Spring source code I found that Spring uses `Assert` Util class for that purpose. And we started to use this class as a replacement. Now code become better with this one line.
Assert.notNull(user, "user must not be empty");

Assert class has many useful methods like
Assert.isTrue
Assert.isNull
Assert.notNull
Assert.hasLength
Assert.hasText
Assert.doesNotContain
Assert.notEmpty
...

If throwing IllegalArgumentException is not good for you then you can create your own Util class for that purpose.