Null Object Pattern - Example

Example

Given a binary tree, with this node structure:

class node { node left node right }

One may implement a tree size procedure recursively:

function tree_size(node) { return 1 + tree_size(node.left) + tree_size(node.right) }

Since the child nodes may not exist, one must modify the procedure by adding non-existence or null checks:

function tree_size(node) { set sum = 1 if node.left exists { sum = sum + tree_size(node.left) } if node.right exists { sum = sum + tree_size(node.right) } return sum }

This however makes the procedure more complicated by mixing boundary checks with normal logic, and it becomes harder to read. Using the null object pattern, one can create a special version of the procedure but only for null nodes:

function tree_size(node) { return 1 + tree_size(node.left) + tree_size(node.right) } function tree_size(null_node) { return 0 }

This separates normal logic from special case handling, and makes the code easier to understand.

Read more about this topic:  Null Object Pattern

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)