Learning Outcomes - 24th March
Null Object Pattern
Today, I focused my learning on implementing the null object pattern in the current tic tac toe web API project. This pattern helps to handle cases where the code may return nil and yet some operations are expected to occur on the result. In my case, one of the instances I applied this was while trying to read the data from a game through a Datastore object, I pass the id of the game and also the key which could be the state, turn, etc of the game.
So my method looked like this:def load(game_id, key)
@datastore.dig(game_id, key)
So this returns the data found in the datastore nested hash with the gameid as the key for the outer hash and the key as the key for the inner hash. From the value retured, I can then use it to set the current state.
The problem with this is that incase the keys are not found, it returns a nil object and when you try to call methods on this nil object, you will get a NoMethodError.
One way to fix this is by surroundnig your calls to this #load method with a nil check and proceeding appropriately as shown below.data = load(id, key)
if data
data.some_method
else
# perform default action
The problem with the above approach is that you have to surround the code with the null check every time you want to use the #load
method. A better approach to solving this would be creating a null class for the datastore, that has the same properties as the actual datastore class the nil check is performed only once in the load method. So if the result is null, the null object is called instead and thus since it has similar properties as the actual datastore call, when you call other methods on it, it doesn’t break the code.
How I implemented the pattern