
APPLIED DESIGN PATTERNS
Stop Checking for Nulls
Let’s have a look at an alternative approach
This is probably against all advice you’ve read so far — unless you’re familiar with the Null Object pattern.
Even if you’ve grasped the concept of NOP, you might still wonder how this is actually done in production ready code.
For anyone who’s still wondering what the null object pattern is all about, read the short introduction below.
Your application explodes when you try invoking methods or accessing properties of a null reference.
Let’s avoid this by applying a very simple but effective pattern. That is, to return a suitable substitution for null. An object that does nothing but improving readability and code safety.
Sounds nice to not having your application explode on you with this screen, right?

So, how do we avoid these nasty looking exceptions if we aren’t checking for nulls anymore?
We’ll take a look at how I’ve successfully applied the Null Object Pattern in applications for large clients.
It’s basically a three step process
- Create your class, whatever it may be
- Define a static Factory Method and make the constructor private
- Create a nested sub-class — this one will be the “null” class
Demo time, finally I’ve created a Person class to demonstrate this, as I assume everyone can relate to what a Person class might be despite however socially impaired we are as programmers.

Okay, let’s break this one down — I’m sure a lot of you will be very skeptical about the factory method over public constructor shenanigans.
At this point, we’ve just added complexity.
Let’s combine the Null Object Pattern with a repository
Nothing special at all, except one thing.

ThatGetPersonByName()` will always return a person. You won’t have to worry about attempting to access properties or methods of a null reference. The method delivers on its promise to always return a Person type.
If you mistakenly forget to write the infamous if(someObj == null){}` it will not wreck your whole GUI with crazy looking exceptions that’ll have your product owner wondering when it’s possible to have an AI do your work.
Test time
No fun without tests. Stop the video whenever you like to read thru the test code.





