Monday, January 13, 2014

No Null Checks: Null Object Pattern

I have a instance of a class that might be missing, in which case the reference is null.
Use the NullObject pattern in place of null checks.


The null object pattern seeks to use an alternative, default or no-operation instance in place of a null
reference.  Instead of having an object reference point to null it points to the "default" or "missing" instance.

The default instance needs to be able to be able to stand-in for the real instance within the code base.  Code using the default instance should be able to call methods and interact with a default instance and produce the correct results (the Liskov substation principle applies).

Example Using a class
In the JobRole class example above we need to create a "null object" stand-in.  Here I create an UnknownJobRole class that extends JobRole.  The class that instantiates the Employee object graph then needs to know to use the UnknownJobRole class when an employee does not have a JobRole.  This class will override any method in JobRole so it can be used in its place.

This code returns false for the two methods I have in the JobRole class. This seems reasonable but in some cases is difficult to assign a default value for missing data.

Now that I don't need to worry about the jobRole instance being null I can revise my method.




Example Using Enum
When defining Enums, if the value could be missing be sure to add a default or unknown value. These null object enums are also handy if you need to sort a collection instances by the enum value. Remember enums will sort based on their ordinal (the order they are defined within the enum class).




Using a collection
A simple way to avoid null checks for collections is to always use an empty collection. A empty collection can be viewed as a type of null object pattern implementation. The Collections class in Java 8 has been expanded to include several convenient methods to help with empty collections.



Summary
The null object pattern is the place to start when dealing with null values, especially in your domain classes. It is an elegant solution to the problem. However, it doesn't work for every situation and can introduce needless complexity.  Pick the right solution for the problem at hand and don't let anyone tell you the Null Object Pattern is the only correct way to deal with nulls.

Wednesday, January 8, 2014

Refactor: Extract if statements to Enum + Lambdas

This post is a follow-up to my Refactor: Extract if statements to Enum post.  In this entry I make the enum implementation a bit more concise using Java 8 lambdas.

In the previous blog we refactored the "if logic" into an enum.  The FrameType enum then knew how to calculate the score for the frame with the appropriate point bonus for strikes and spares.

Now I want to specify the logic as a functional interface. This approach expresses the same logic but in a condensed style without the ceremony overriding an abstract method. I have also refactored the rolls in frame to be a member variable - which is convenient using the enum constructor.

The scoreFrame logic is moved into a java.util.function.BiFunction instance. BiFunction<T, U, R> is a function that takes two objects, of type T and U. and returns an Object of type R. The lambda is supplied as an argument in the constructor and kept as a member of the enum instance.

The scoreFrame method changes from abstract to simply applying the function and returning the result. No changes in the BowlingGame class that uses the enum.

The result is a bit more concise, we have overcome some of the vertical space needed to express the old solution.  Does it read better?  Is it clear what the lambda does?  Let me know what you think…is it better?

Monday, January 6, 2014

Refactor: Extract If statements to Enum

When a method's logic gets complex it can indicate we are missing an abstraction.  In this entry I highlight how Java's enum can be a simple abstraction that simplifies your logic and improves
code readability.  As a starting point I use a class from the bowling game kata.

Additional background information about the bowling game kata can be found here The Bowling Game Kata.

The refactoring step applied introduces an enum to represent the frame type and moves the scoring logic to the enum instance.  This simple technique can be used to simplify code by adding simple abstractions.

I'm going to focus my refactoring on the score method (which scores a bowling games based on the frames bowled) that at the end of the kata looks like this:

The score method has a nested if else statement that I would like to simplify. Often, when code seems complex it can indicate you are missing a concept. In this case I think introducing a class that represents the type of frame reduces the complexity and makes the code easier to understand. The FrameType enum represents how the player scored in a Frame - Strike, Spare or Open (meaning not all the pins were knocked down). The classifyFrame method determines the applicable type based on one or two rolls.


Now that I can classify the frame I think the enum should know how to compute the score for the frame. Since each FrameType instance has a slightly different score calculation I am defining an abstract method within the enum. Then each enum instance will define its specific implementation.


This is the final version of the class. The rollsInFrame method is another behavior that is specific to each frame type. As you can see this refactoring removed the if else structure from the method. The score method now highlights the top level logic and the details are in the enum.

Introducing an enum is a simple way to encapsulate different logic into objects versus using if statements (a OO technique called polymorphism). In the right context this is a powerful tool to simplify and improve code readability.  Using an enum is a simple way to introduce a new object and harness polymorphism.  If your needs evolve the implementation can become classes and that inherit from a FrameType super class.  There is nothing in the code that calls the scoreFrame method specific to our chosen enum solution.

At a high-level most people know that in bowling spares and strikes are scored differently. The BowlingGame class now tells that story.

Can we do better?

The score method seems ok - it is expressive, the level of abstraction is the same for each statement.  I don't always like using the += operator.  Why is the enum called FrameType? Is there a better name?

The FrameType enum makes sense, I think it reads fine.  It does seem horizontally challenged.  There are a lot of statements, somewhat due to Java language constructs.  What other options do we have?  Maybe functional lambdas?