Null Object

Null object design pattern is to make use of the object, be it not declared or having no value to be as a value. This allows a system to operate even at the absent of values or using such phenomenon to set "do nothing" action. This is often deployed in Singleton creational pattern. The design diagram is as follows:

When To Use (Problems)

  • When the problem requires handling of non-declared or non-initialized values.
  • When the problem requires a default do nothing parameter.

Example (Solution)

Here is an example in Go:

package main

import (
        "fmt"
)

func Print(d interface{}) {
        if d == nil {
                return
        }

        fmt.Printf("the value is: %v\n", d)
}

func main() {
        Print("Hello")
        Print(5)
        Print(nil)
}
// Output:
// the value is: Hello
// the value is: 5

Notice that when given nil to the Print function, the function does nothing. This allows us to tell the function to "do nothing" instead of allocating some forms of flags.

Expected Outcome (Consequences)

  • null object is used as a value or as an indicator of do nothing instead of reserving a value or introducing another flag indicator.