javadesign-patternsbinary-search-treenull-object-pattern

Ways to implement Null Object Pattern


Till now I have seen everywhere that the steps to create Null Object Pattern, for example in BST to remove null checks, are as follows:

  1. Create an interface Node

  2. Create two classes implementing the interface Node. One of which will be real_Node and other will be null_Node.

  3. Using those classes, null checks can be removed in BST class while creating the tree.

Now I want to know that, are there other ways to do this, e.g., Can we implement Null Object Pattern without interface using only classes, i.e. in the above step (1.) can we use Node class instead of Node interface


Solution

  • Yes, there are ways to implement the Null object pattern without explicitly using a Java interface. However, you are really doing much the same thing so YMMV. You might find problems if you don't have access to the base class and/or it doesn't allow for some form of extending/overriding.

    Alternatively, sometimes a NULL-object is really just a special case of a particular value (it really depends on what the operations on the class are). In that case you could either have a static member with that value or a static factory which allows you to create it.