DEV Community

Discussion on: Unhealthy Code: Null Checks Everywhere!

 
jamesmh profile image
James Hickey

I disagree with the notion that "just adding a null check in the constructor" is always the best solution.

The fact is that any solution you choose is going to have trade-offs.

I've written about using constructor validation here and I agree that there are some contexts when using this technique is the best choice.

That being said, there are trade-offs to using constructor validation:

Mainly: You have to throw an exception to notify the caller that they did something wrong.

The caller (and developer using your class) has to have implicit knowledge up-front that your class will throw when used incorrectly. That can lead to developers potentially using your class wrong.

This also depends on whether your code is a publically accessible library or custom/internal business logic for a company.

With a public library, you aren't guaranteed to be able to educate users of the fact that your class will throw (other than in documentation, them finding out "the hard way", etc.)

What if that person wants to use your library in a performance-sensitive context? Throwing exceptions has a huge performance impact... so they may not opt for your library now.

The same applies to custom business code: does it need to be used in a performance-sensitive context? If so, throwing exceptions is the first offender to that most devs will look at removing.

Now, looking at the technique in this article, it allows the caller to not have to know about nulls and having to check them. Sure, it's a different technique, but now you have hidden/encapsulated the need to check for nulls, it's more performant since you don't need to catch exceptions, etc.

Is it a bit more complicated (internally)? Sure. But that's the price you pay in order to make code that's easier to use or has less of an entry barrier.

SOOO... which way is best?

Well, it depends! And that comes back to my comments with @hegi - just saying that one technique works best in all contexts across the board leads to issues when perhaps the context in question is something like a performance-sensitive, etc.

This is the same thinking people have when they say that "microservices is the best architecture and should always use it." That attitude and approach can (and has) destroy companies when used in the wrong context.

Thanks for your thoughts @alexander !