When can you implement a Null Object? When the return types of your methods are monoids.

This article is part of a series of articles about design patterns and their category theory counterparts. In a previous article you learned how there's a strong relationship between the Composite design pattern and monoids. In this article you'll see that the Null Object pattern is essentially a special case of the Composite pattern.

I also think that there's a relationship between monoidal identity and the Null Object pattern similar to the relationship between Composite and monoids in general:

Once more, I don't claim that an isomorphism exists. You may be able to produce Null Object examples that aren't monoidal, but on the other hand, I believe that all identities are Null Objects.

Null Object #

While the Null Object design pattern isn't one of the patterns covered in Design Patterns, I consider it a structural pattern because Composite is a structural pattern, and Null Object is a special case of Composite.

Bobby Woolf's original text contains an example in Smalltalk, and while I'm no Smalltalk expert, I think a fair translation to C# would be an interface like this:

public interface IController { bool IsControlWanted(); bool IsControlActive(); void Startup(); }

The idea behind the Null Object pattern is to add an implementation that 'does nothing', which in the example would be this:

public class NullController : IController { public bool IsControlActive() { return false ; } public bool IsControlWanted() { return false ; } public void Startup() { } }

Woolf calls his implementation NoController , but I find it more intent-revealing to call it NullController . Both of the Boolean methods return false , and the Startup method literally does nothing.

Doing nothing #

What exactly does it mean to 'do nothing'? In the case of the Startup method, it's clear, because it's a bona fide no-op. This is possible for all methods without return values (i.e. methods that return void ), but for all other methods, the compiler will insist on a return value.

For IsControlActive and IsControlWanted , Woolf solves this by returning false .

Is false always the correct 'do nothing' value for Booleans? And what should you return if a method returns an integer, a string, or a custom type? The original text is vague on that question:

"Exactly what "do nothing" means is subjective and depends on the sort of behavior the Client is expecting."

Doing nothing as identity #

Sometimes, you can't get any closer than that, but I think that often it's possible to be more specific.

From unit isomorphisms you know that methods without return values are isomorphic to methods that return unit. You also know that unit is a monoid. What does unit and bool have in common? They both form monoids; bool , in fact, forms four different monoids, of which all and any are the best-known.

In my experience, you can implement the Null Object pattern by returning various 'do nothing' values, depending on their types:

For bool , return a constant value. Usually, false is the appropriate 'do nothing' value, but it does depend on the semantics of the operation.

, return a constant value. Usually, is the appropriate 'do nothing' value, but it does depend on the semantics of the operation. For string , return "" .

, return . For collections, return an empty collection.

For numbers, return a constant value, such as 0 .

. For void , do nothing, which is equivalent to returning unit.

bool

int

The identity for the any monoid is false .

. The identity for string is "" .

is . The identity for collections is the empty collection.

The identity for the addition monoid is 0 .

. The identity for unit is unit.

What all of these have in common is that they return the identity of the monoid in question. Keep in mind that for some types, such asand, more than one monoid exist, and the identity depends on which one you pick:Recall what the identity of a monoid is: it's the value that, when applied to another value, doesn't change the other value:

foo.Op( Foo .Identity) == foo

In other words: the identity does nothing!

As a preliminary result, then, when all return values of your interface form monoids, you can create a Null Object.

Relationship with Composite #

In the previous article, you saw how the Composite design pattern was equivalent with the Haskell function mconcat :

mconcat :: Monoid a => [a] -> a

This function, however, seems more limited than it has to be. It says that if you have a linked list of monoidal values, you can reduce them to a single monoidal value. Is this only true for linked lists?

After all, in a language like C#, you'd typically express a Composite as a container of 'some collection' of objects, typically modelled by the IReadOnlyCollection<T> interface. There are several implementations of that interface, including lists, arrays, collections, and so on.

It seems as though we ought to be able to generalise mconcat , and, indeed, we can. The Data.Foldable module defines a function called fold :

fold :: (Monoid m, Foldable t) => t m -> m

Let me decipher that for you. It says that any monoid m contained in a 'foldable' container t can be reduced to a single value (still of the type m ). You can read t m as 'a foldable container that contains monoids'. In C#, you could attempt to express it as IFoldable<TMonoid> .

In other words, the Composite design pattern is equivalent to fold . Here's how it relates to the Null Object pattern:

As a first step, consider methods like those defined by the above IController interface. In order to implement NullController , all of those methods ignore their (non-existent) input and return an identity value. In other words, we're looking for a Haskell function of the type Monoid m => a -> m ; that is: a function that takes input of the type a and returns a monoidal value m .

You can do that using fold :

nullify :: Monoid m => a -> m nullify = fold ( Identity $ const mempty)

Recall that the input to fold must be a Foldable container. The good old Identity type is, among other capabilities, Foldable . That takes care of the container. The value that we put into the container is a single function that ignores its input ( const ) and always returns the identity value ( mempty ). The result is a function that always returns the identity value.

This demonstrates that Null Object is a special case of Composite, because nullify is a special application of fold .

There's no reason to write nullify in such a complicated way, though. You can simplify it like this:

nullify :: Monoid m => a -> m nullify = const mempty

Once you recall, however, that functions are monoids if their return values are monoids, you can simplify it even further:

nullify :: Monoid m => a -> m nullify = mempty

The identity element for monoidal functions is exactly a function that ignores its input and returns mempty .

Controller identity #

Consider the IController interface. According to object isomorphisms, you can represent this interface as a tuple of three functions:

type Controller = ( ControllerState -> Any , ControllerState -> Any , ControllerState -> () )

This is cheating a little, because the third tuple element (the one that corresponds to Startup ) is pure, although I strongly suspect that the intent is that it should mutate the state of the Controller. Two alternatives are to change the function to either ControllerState -> ControllerState or ControllerState -> IO () , but I'm going to keep things simple. It doesn't change the conclusion.

Notice that I've used Any as the return type for the two first tuples. As I've previously covered, Booleans form monoids like any and all. Here, we need to use Any .

This tuple is a monoid because all three functions are monoids, and a tuple of monoids is itself a monoid. This means that you can easily create a Null Object using mempty :

λ> nullController = mempty :: Controller

The nullController is a triad of functions. You can access them by pattern-matching them, like this:

λ> (isControlWanted, isControlActive, startup) = nullController

Now you can try to call e.g. isControlWanted with various values in order to verify that it always returns false. In this example, I cheated and simply made ControllerState an alias for String :

λ> isControlWanted "foo" Any {getAny = False} λ> isControlWanted "bar" Any {getAny = False}

You'll get similar behaviour from isControlActive , and startup always returns () (unit).

As Woolf wrote in the original text, what 'do nothing' means is subjective. I think it's perfectly reasonable to say that monoidal identity fits the description of doing nothing, but you could probably encounter APIs where 'doing nothing' means something else.

As an example, consider avatars for online forums, such as Twitter. If you don't supply a picture when you create your profile, you get a default picture. One way to implement such a feature could be by having a 'null' avatar, which is used in place of a proper avatar. Such a default avatar object could (perhaps) be considered a Null Object, but wouldn't necessarily be monoidal. There may not even be a binary operation for avatars.

Thus, it's likely that you could encounter or create Null Objects that aren't monoids. That's the reason that I don't claim that a Null Object always is monoidal identity, although I do think that the reverse relationship holds: if it's identity, then it's a Null Object.

Monoids are associative binary operations with identity. The identity is the value that 'does nothing' in that binary operation, like, for example, 0 doesn't 'do' anything under addition. Monoids, however, can be more complex than operations on primitive values. Functions, for example, can be monoids as well, as can tuples of functions.

The implication of that is that objects can be monoids as well. When you have a monoidal object, then its identity is the 'natural' Null Object.

The question was: when can you implement the Null Object pattern? The answer is that you can do that when all involved methods return monoids.

Next: Builder as a monoid.