Home of the AlmostImplementedException

Null Object Pattern

As announced in my previous post about Introducing Design Patterns, I will start with the first concrete post about the “Null Object Pattern”. For this I will take the chess board example from Indexed Properties.
What is the Null Object Pattern? It is a design pattern that belongs to the “Behavioral patterns”. This object does nothing. It is representative for nothing. The following UML diagramm will explain the simple structure.

Null Object (UML)

So, why we don’t simply use null instead of this “Null object”? One reason is to prevent “Null reference exceptions”. Another advantage is to use null objects together with “The Visitor Pattern” (I will explain it, in a following post). Let’s get practical. In our chess board example we have used indexed properties to get the specified field on the board. Now it’s time to fill the field with live. But first let’s take a look at the current Field class.

I think the ToString method is very lonely – So lets add some stuff. Lets add a new property called “Value” that contains a value from a new class “Figure”. This class is abstract, because we derive the concrete chess figures from it. Furthermore we want to add the initialization into the Board class. Let’s do that in one step (Sorry for the long code, but I think it’s better that we have one base for the following steps). We will ignore the behaviour of each figure in our example, like start and end position, and movement validation, because we will focus on the structure – and I want to tell you something about the “Null Object Pattern” 😉

Now our chess board is filled with figure at initial positions and we can easily call “ExecuteAction” for the figure at “C2”. You will see, that we get “I’m a Pawn” as output.

But what is when we call “ExecuteAction” for “C3”? Because there is no figure on it, we will get a NullReferenceException. To prevent this, we have to check for null.

I think you will agree, that this is not an elegant way. This is the point where the “Null Object Pattern” makes sense.
Now we have to do two things: Create An “Empty” class derived from “Figure”. And assign that to all fields with no value. In our example we will do that in the Reset method where we create/assign the figures.

We are now able to call “ExecuteAction” on a field that has no figure – and it will simply do nothing.

Maybe you think: “To much effort – Checking for null will also meet the needs.” Yes maybe you’re right, but if you have more complex code and use those objects in many places, you have to check for null every single time – and it can easily happen, that you miss one check 😉
In the next post about “Design Patterns” I will talk about the “Visitor Pattern”, that is a good following to this.
Hope you enjoyed this post. Have a nice day!

Share :

, , , , ,

Leave a Reply