I was working on a state machine implementation today and faced with a scenario that I need to introduce lots of code for an one-time-check-only situation. It was

  1. Initialize the state machine object via init()  method
  2. Set the new state via changeState() method.

The code was like this:

And I faced with the very famous null pointer exception in C++. Then, I checked the state machine code I wrote many months ago. The changeState() method was like this:

Very reasonable code for a method that I will call frequently. While checking changeState() method I remembered the constructors of the state machine:

It was obvious that mCurrentState would be NULL for the call I made right after initializing the state machine and I needed to right some if-then code for preventing this. The only problem, I knew that I would need this if-then code only once at the beginning of the execution, but it would remain with the code and perform this useless if-then check whenever I want to change the state. So, I was not very keen to go for if-then implementation.

Then, I remembered null object, an object that does not do anything except saving you handling NULL with if…else statement. So, I added an extra class to my project:

and replaced my constructors as:

Thanks to null object pattern I was able to save myself from null pointer exception without changing changeState() method. It also helped me to turn these lines below

to these ones:

I believe this is cleaner, less error prone, and easier to read.

Here is the whole code of State and StateMachine classes in case you would like to see: