Null Object Design Pattern

T

Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides intelligent do nothing behavior, hiding the details from its collaborators. Originally written up by Bobby Wolf, in Pattern Languages of Program Design 3

250    Design Patterns Course




      Null Object
      Intent
      Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides
      intelligent do nothing behavior, hiding the details from its collaborators.

      Also Known as
      Stub, Active Nothing

      Motivation
      Sometimes a class that requires a collaborator does not need the collaborator to do anything. However,
      the class wishes to treat a collaborator that does nothing the same way it treats one that actually
      provides behavior.

      Consider for example a simple screen saver which displays balls that move about the screen and have
      special color effects. This is easily achieved by creating a Ball class to represent the balls and using a
      Strategy pattern [GHJV95, page 315] to control the ball's motion and another Strategy pattern to control
      the ball's color. It would then be trivial to write strategies for many different types of motion and color
      effects and create balls with any combination of those. However, to start with you want to create the
      simplest strategies possible to make sure everything is working. And these strategies could also be
      useful later since you want as strategies as possible strategies.

      Now, the simplest strategy would be no strategy. That is do nothing, don't move and don't change color.
      However, the Strategy pattern requires the ball to have objects which implement the strategy
      interfaces. This is where the Null Object pattern becomes useful. Simply implement a
      NullMovementStrategy which doesn't move the ball and a NullColorStrategy which doesn't change the
      ball's color. Both of these can probably be implemented with essentially no code. All the methods in
      these classes do quot;nothingquot;. They are perfect examples of the Null Object Pattern.

      The key to the Null Object pattern is an abstract class that defines the interface for all objects of this
      type. The Null Object is implemented as a subclass of this abstract class. Because it conforms to the
      abstract class' interface, it can be used any place this type of object is needed. As compared to using a
      special quot;nullquot; value which doesn't actually implement the abstract interface and which must constantly
      be checked for with special code in any object which uses the abstract interface.

      It is sometimes thought that Null Objects are over simple and quot;stupidquot; but in truth a Null Object always
      knows exactly what needs to be done without interacting with any other objects. So in truth it is very
      quot;smart.quot;




      * This patterns was originally written up by Bobby Wolf, in Pattern Languages of Program Design 3
Null Object   251
252    Design Patterns Course



      Applicability
      Use the Null Object pattern when:

              an object requires a collaborator. The Null Object pattern does not introduce this collaboration--
              it makes use of a collaboration that already exists.
              some collaborator instances should do nothing.
              you want to abstract the handling of null away from the client.

      Participants
              Client
                  o requires a collaborator.
              AbstractObject
                  o declares the interface for Client's collaborator.
                  o implements default behavior for the interface common to all classes, as appropriate.
              RealObject
                  o defines a concrete subclass of AbstractObject whose instances
                  o provide useful behavior that Client expects.
              NullObject
                  o provides an interface identical to AbstractObject's so that a null object can be
                      substituted for a real object.
                  o implements its interface to do nothing. What exactly it means to do nothing depends on
                      what sort of behavior Client is expecting.
                  o when there is more than one way to do nothing, more than one NullObject class may be
                      required.

      Collaborations
      Clients use the AbstractObject class interface to interact with their collaborators. If the receiver is a
      RealObject, then the request is handled to provide real behavior. If the receiver is a NullObject, the
      request is handled by doing nothing or at least providing a null result.

      Consequences
      The Null Object pattern:

              defines class hierarchies consisting of real objects and null objects. Null objects can be used in
              place of real objects when the object is expected to do nothing. Whenever client code expects a
              real object, it can also take a null object.
              makes client code simple. Clients can treat real collaborators and null collaborators uniformly.
              Clients normally don't know (and shouldn't care) whether they're dealing with a real or a null
              collaborator. This simplifies client code, because it avoids having to write testing code which
              handles the null collaborator specially.
              encapsulates the do nothing code into the null object. The do nothing code is easy to find. Its
              variation with the AbstractObject and RealObject classes is readily apparent. It can be efficiently
Null Object     253


           coded to do nothing. It does not require variables that contain null values because those values
           can be hard-coded as constants or the do nothing code can avoid using those values altogether.
           makes the do nothing code in the null object easy to reuse. Multiple clients which all need their
           collaborators to do nothing will all do nothing the same way. If the do nothing behavior needs to
           be modified, the code can be changed in one place. Thereafter, all clients will continue to use
           the same do nothing behavior, which is now the modified do nothing behavior.
           makes the do nothing behavior difficult to distribute or mix into the real behavior of several
           collaborating objects. The same do nothing behavior cannot easily be added to several classes
           unless those classes all delegate the behavior to a class which can be a null object class.
           can necessitate creating a new NullObject class for every new AbstractObject class.
           can be difficult to implement if various clients do not agree on how the null object should do
           nothing as when your AbstractObject interface is not well defined.
           always acts as a do nothing object. The Null Object does not transform into a Real Object.




Figure 87 - Before and After - Null Object pattern gets rif of quot;ifquot; statements
254    Design Patterns Course



      Implementation
      There are several issues to consider when implementing the Null Object pattern:

        1. Null Object as Singleton. The Null Object class is often implemented as a Singleton [GHJV95, page
      127]. Since a null object usually does not have any state, its state can't change, so multiple instances are
      identical. Rather than use multiple identical instances, the system can just use a single instance
      repeatedly.

        2. Clients don't agree on null behavior. If some clients expect the null object to do nothing one way
      and some another, multiple NullObject classes will be required. If the do nothing behavior must be
      customized at run time, the NullObject class will require pluggable variables so that the client can
      specify how the null object should do nothing (see the discussion of pluggable adaptors in the Adapter
      pattern [GHJV95, page 142]). This may generally be a symptom of the AbstractObject not having a well
      defined (semantic) interface.

        3. Transformation to Real Object. A Null Object does not transform to become a Real Object. If the
      object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null
      object. It may be a real object with a do nothing mode, such as a controller which can switch in and out
      of read-only mode. If it is a single object which must mutate from a do nothing object to a real one, it
      should be implemented with the State pattern [GHJV95, page 305] or perhaps the Proxy pattern
      [GHJV95, page 207]. In this case a Null State may be used or the proxy may hold a Null Object.

         4. Null Object is not Proxy. The use of a null object can be similar to that of a Proxy [GHJV95, page
      207], but the two patterns have different purposes. A proxy provides a level of indirection when
      accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real
      object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting
      like a real subject. A null object will not mutate to start providing real behavior, it will always provide do
      nothing behavior.

        5. Null Object as special Strategy. A Null Object can be a special case of the Strategy pattern [GHJV95,
      page 315]. Strategy specifies several ConcreteStrategy classes as different approaches for accomplishing
      a task. If one of those approaches is to consistently do nothing, that ConcreteStrategy is a NullObject.
      For example, a Controller is a View's Strategy for handling input, and NoController is the Strategy that
      ignores all input.

        6. Null Object as special State. A Null Object can be a special case of the State pattern [GHJV95, page
      305]. Normally, each ConcreteState has some do nothing methods because they're not appropriate for
      that state. In fact, a given method is often implemented to do something useful in most states but to do
      nothing in at least one state. If a particular ConcreteState implements most of its methods to do nothing
      or at least give null results, it becomes a do nothing state and as such is a null state. [Woolf96]

        7. Null Object as Visitor host. A Null Object can be used to allow a Visitor [GHJV95, page 331] to safely
      visit a hierarchy and handle the null situation.
Null Object   255


  8. The Null Object class is not a mixin. Null Object is a concrete collaborator class that acts as the
collaborator for a client which needs one. The null behavior is not designed to be mixed into an object
that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of
the behavior that may or may not be do nothing behavior. [Woolf96]




Figure 88 - Using Null Object pattern for Mocking Databases


Andy Tips:
          A Null Object provides a surrogate for another object that shares the same interface, but does
          nothing.
          Thus the Null Object encapsulates the implementation decisions of how to do nothing and hides
          those details from its collaborators.
256    Design Patterns Course




      Code:
      Without Null Object


      from time import asctime, localtime

      class RealLogging:
          def Log(self, msg):
              print 'Logged at', asctime(localtime()), msg

      # Proxy / wrapper around either null or real logger.

      class Logger:
          def __init__(self):
              self.logger = RealLogging()
          def Log(self, msg):
              if self.logger:
                  self.logger.Log(msg)
          def On(self):
              self.logger = RealLogging()
          def Off(self):
              self.logger = None
      Logger = Logger()

      # Usage:

      class API:
          def doA(self):
              if Logger.logger:
                  Logger.Log('Am calling A')
              print 'A done.'
          def doB(self):
              if Logger.logger:
                  Logger.Log('Am calling B')
              print 'B done.'

      o = API()
      o.doA()
      o.doB()
Null Object   257



Logger.Off()
o.doA()
o.doB()




With Null Object


# Null Object Pattern

class AbstractLogging:
    def Log(self, msg): pass

from time import asctime, localtime

class RealLogging(AbstractObject):
    def Log(self, msg):
        print 'Logged at', asctime(localtime()), msg

class NullLogging(AbstractObject):
    def Log(self, msg):
        return

# Proxy / wrapper around either null or real logger.

class Logger:
    def __init__(self):
        self.On()
    def Log(self, msg):
        self.logger.Log(msg)
    def On(self):
        self.logger = RealLogging()
    def Off(self):
        self.logger = NullLogging()
Logger = Logger()

# Usage:

class API:
    def doA(self):
        Logger.Log('Am calling A')
        print 'A done.'
    def doB(self):
        Logger.Log('Am calling B')
        print 'B done.'

o = API()
o.doA()
258    Design Patterns Course


      o.doB()

      Logger.Off()
      o.doA()
      o.doB()

      Notice – no more “if” statements in the client code (API class).

      Notes:

Recommended

Garbage collection by
Garbage collectionGarbage collection
Garbage collectionMudit Gupta
1.4K views20 slides
Concurrency in Java by
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
2.7K views49 slides
Java concurrency - Thread pools by
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
5.6K views35 slides
Abusing Adobe Reader’s JavaScript APIs by Abdul-Aziz Hariri & Brian Gorenc - ... by
Abusing Adobe Reader’s JavaScript APIs by Abdul-Aziz Hariri & Brian Gorenc - ...Abusing Adobe Reader’s JavaScript APIs by Abdul-Aziz Hariri & Brian Gorenc - ...
Abusing Adobe Reader’s JavaScript APIs by Abdul-Aziz Hariri & Brian Gorenc - ...CODE BLUE
2.2K views46 slides
Patrones de diseño en la automatización PageObject o ScreenPlay by
Patrones de diseño en la automatización PageObject o ScreenPlayPatrones de diseño en la automatización PageObject o ScreenPlay
Patrones de diseño en la automatización PageObject o ScreenPlayAbel Quintana Lopez
2.5K views40 slides
Spring Framework - Validation by
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - ValidationDzmitry Naskou
4.9K views25 slides

More Related Content

What's hot

Hibernate caching by
Hibernate cachingHibernate caching
Hibernate cachingAlex Verdyan
3.1K views28 slides
Window object by
Window objectWindow object
Window objectpreetikapri1
110 views8 slides
Minimization of Boolean Functions by
Minimization of Boolean FunctionsMinimization of Boolean Functions
Minimization of Boolean Functionsblaircomp2003
6.3K views24 slides
Object Oriented Programming with Java by
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
12.9K views105 slides
Threads in JAVA by
Threads in JAVAThreads in JAVA
Threads in JAVAHaldia Institute of Technology
17.7K views14 slides
Cs 361 2015 lec 1-2 by
Cs 361 2015 lec 1-2Cs 361 2015 lec 1-2
Cs 361 2015 lec 1-2Alaa Zaghloul
1.1K views21 slides

What's hot(20)

Hibernate caching by Alex Verdyan
Hibernate cachingHibernate caching
Hibernate caching
Alex Verdyan3.1K views
Minimization of Boolean Functions by blaircomp2003
Minimization of Boolean FunctionsMinimization of Boolean Functions
Minimization of Boolean Functions
blaircomp20036.3K views
Object Oriented Programming with Java by Jussi Pohjolainen
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen12.9K views
Java Performance and Profiling by WSO2
Java Performance and ProfilingJava Performance and Profiling
Java Performance and Profiling
WSO22.3K views
Prototype pattern by Shakil Ahmed
Prototype patternPrototype pattern
Prototype pattern
Shakil Ahmed6.7K views
Strings in Java by Hitesh-Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java434 views
Java Constructors by Saumya Som
Java ConstructorsJava Constructors
Java Constructors
Saumya Som327 views
J - K & MASTERSLAVE FLIPFLOPS by Krishma Parekh
J - K & MASTERSLAVE FLIPFLOPSJ - K & MASTERSLAVE FLIPFLOPS
J - K & MASTERSLAVE FLIPFLOPS
Krishma Parekh12.3K views
Looping statements in Java by Jin Castor
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor13.6K views
Datatype in JavaScript by Rajat Saxena
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
Rajat Saxena1.2K views
Java String by Java2Blog
Java StringJava String
Java String
Java2Blog507 views
Garbage collection by Somya Bagai
Garbage collectionGarbage collection
Garbage collection
Somya Bagai7.5K views
An Introduction To Java Profiling by schlebu
An Introduction To Java ProfilingAn Introduction To Java Profiling
An Introduction To Java Profiling
schlebu5.3K views

Viewers also liked

The Null Object Pattern by
The Null Object PatternThe Null Object Pattern
The Null Object Patternmodern_legend
3.5K views26 slides
Null object pattern by
Null object patternNull object pattern
Null object patternJuggernaut Liu
298 views21 slides
design patterns java by
design patterns javadesign patterns java
design patterns javaRogerio da Silva
2K views125 slides
PATTERNS02 - Creational Design Patterns by
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael Heron
1.9K views27 slides
Design Patterns Presentation - Chetan Gole by
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
12.1K views24 slides
Design patterns by
Design patternsDesign patterns
Design patternsabhisheksagi
14.9K views28 slides

Viewers also liked(8)

The Null Object Pattern by modern_legend
The Null Object PatternThe Null Object Pattern
The Null Object Pattern
modern_legend3.5K views
PATTERNS02 - Creational Design Patterns by Michael Heron
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
Michael Heron1.9K views
Design Patterns Presentation - Chetan Gole by Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
Chetan Gole12.1K views
Design patterns by abhisheksagi
Design patternsDesign patterns
Design patterns
abhisheksagi14.9K views
Design patterns ppt by Aman Jain
Design patterns pptDesign patterns ppt
Design patterns ppt
Aman Jain28.8K views
Software design patterns ppt by mkruthika
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
mkruthika29.9K views

Similar to Null Object Design Pattern

Something for Nothing by
Something for NothingSomething for Nothing
Something for NothingKevlin Henney
853 views4 slides
Jump start to OOP, OOAD, and Design Pattern by
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
9.8K views58 slides
Jump Start To Ooad And Design Patterns by
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
1.2K views58 slides
Design Patterns in Ruby by
Design Patterns in RubyDesign Patterns in Ruby
Design Patterns in RubyMindfire Solutions
830 views19 slides
Abstract by
AbstractAbstract
Abstractsnehajyothi
120 views5 slides
Javascript Object Patterns.pptx by
Javascript Object Patterns.pptxJavascript Object Patterns.pptx
Javascript Object Patterns.pptxAlaref Abushaala
23 views34 slides

Similar to Null Object Design Pattern(20)

Jump start to OOP, OOAD, and Design Pattern by Nishith Shukla
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla9.8K views
Jump Start To Ooad And Design Patterns by Lalit Kale
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
Lalit Kale1.2K views
AEM Clean Code - Miklos Csere by Miklos Csere
AEM Clean Code - Miklos Csere AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere
Miklos Csere270 views
Design patterns difference between interview questions by Umar Ali
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
Umar Ali10.4K views
Object Oriented Prograring(OOP) java by GaddafiAdamu1
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
GaddafiAdamu123 views
Mac/iOS Design Patterns by Robert Brown
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design Patterns
Robert Brown7.2K views
Design patterns in javascript by Ayush Sharma
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma125 views
Inverting Dependencies by Luc Trudeau
Inverting DependenciesInverting Dependencies
Inverting Dependencies
Luc Trudeau237 views
GOF Design pattern with java by Rajiv Gupta
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
Rajiv Gupta673 views

More from tcab22

State Pattern In Flex by
State Pattern In FlexState Pattern In Flex
State Pattern In Flextcab22
73 views16 slides
Blackboard Pattern by
Blackboard PatternBlackboard Pattern
Blackboard Patterntcab22
17.8K views12 slides
Tooled Composite Design Pattern by
Tooled Composite Design PatternTooled Composite Design Pattern
Tooled Composite Design Patterntcab22
867 views24 slides
Tooled Composite Design Pattern presentation by
Tooled Composite Design Pattern presentationTooled Composite Design Pattern presentation
Tooled Composite Design Pattern presentationtcab22
410 views24 slides
Andy Bulka Pattern Automation by
Andy Bulka Pattern AutomationAndy Bulka Pattern Automation
Andy Bulka Pattern Automationtcab22
236 views10 slides
Representing Design Patterns In Uml Andy Bulka Oct2006 by
Representing Design Patterns In Uml Andy Bulka Oct2006Representing Design Patterns In Uml Andy Bulka Oct2006
Representing Design Patterns In Uml Andy Bulka Oct2006tcab22
951 views16 slides

More from tcab22(6)

State Pattern In Flex by tcab22
State Pattern In FlexState Pattern In Flex
State Pattern In Flex
tcab2273 views
Blackboard Pattern by tcab22
Blackboard PatternBlackboard Pattern
Blackboard Pattern
tcab2217.8K views
Tooled Composite Design Pattern by tcab22
Tooled Composite Design PatternTooled Composite Design Pattern
Tooled Composite Design Pattern
tcab22867 views
Tooled Composite Design Pattern presentation by tcab22
Tooled Composite Design Pattern presentationTooled Composite Design Pattern presentation
Tooled Composite Design Pattern presentation
tcab22410 views
Andy Bulka Pattern Automation by tcab22
Andy Bulka Pattern AutomationAndy Bulka Pattern Automation
Andy Bulka Pattern Automation
tcab22236 views
Representing Design Patterns In Uml Andy Bulka Oct2006 by tcab22
Representing Design Patterns In Uml Andy Bulka Oct2006Representing Design Patterns In Uml Andy Bulka Oct2006
Representing Design Patterns In Uml Andy Bulka Oct2006
tcab22951 views

Recently uploaded

CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueShapeBlue
93 views15 slides
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...ShapeBlue
101 views17 slides
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...ShapeBlue
123 views28 slides
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueShapeBlue
179 views7 slides
Network Source of Truth and Infrastructure as Code revisited by
Network Source of Truth and Infrastructure as Code revisitedNetwork Source of Truth and Infrastructure as Code revisited
Network Source of Truth and Infrastructure as Code revisitedNetwork Automation Forum
52 views45 slides
Future of AR - Facebook Presentation by
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook PresentationRob McCarty
62 views27 slides

Recently uploaded(20)

CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue93 views
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue101 views
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by ShapeBlue
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
ShapeBlue123 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue179 views
Future of AR - Facebook Presentation by Rob McCarty
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
Rob McCarty62 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue181 views
The Power of Heat Decarbonisation Plans in the Built Environment by IES VE
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built Environment
IES VE69 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely78 views
NTGapps NTG LowCode Platform by Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu365 views
The Role of Patterns in the Era of Large Language Models by Yunyao Li
The Role of Patterns in the Era of Large Language ModelsThe Role of Patterns in the Era of Large Language Models
The Role of Patterns in the Era of Large Language Models
Yunyao Li80 views
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by ShapeBlue
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
ShapeBlue88 views
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue by ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
ShapeBlue103 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue222 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson156 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue98 views

Null Object Design Pattern

  • 1. 250 Design Patterns Course Null Object Intent Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides intelligent do nothing behavior, hiding the details from its collaborators. Also Known as Stub, Active Nothing Motivation Sometimes a class that requires a collaborator does not need the collaborator to do anything. However, the class wishes to treat a collaborator that does nothing the same way it treats one that actually provides behavior. Consider for example a simple screen saver which displays balls that move about the screen and have special color effects. This is easily achieved by creating a Ball class to represent the balls and using a Strategy pattern [GHJV95, page 315] to control the ball's motion and another Strategy pattern to control the ball's color. It would then be trivial to write strategies for many different types of motion and color effects and create balls with any combination of those. However, to start with you want to create the simplest strategies possible to make sure everything is working. And these strategies could also be useful later since you want as strategies as possible strategies. Now, the simplest strategy would be no strategy. That is do nothing, don't move and don't change color. However, the Strategy pattern requires the ball to have objects which implement the strategy interfaces. This is where the Null Object pattern becomes useful. Simply implement a NullMovementStrategy which doesn't move the ball and a NullColorStrategy which doesn't change the ball's color. Both of these can probably be implemented with essentially no code. All the methods in these classes do quot;nothingquot;. They are perfect examples of the Null Object Pattern. The key to the Null Object pattern is an abstract class that defines the interface for all objects of this type. The Null Object is implemented as a subclass of this abstract class. Because it conforms to the abstract class' interface, it can be used any place this type of object is needed. As compared to using a special quot;nullquot; value which doesn't actually implement the abstract interface and which must constantly be checked for with special code in any object which uses the abstract interface. It is sometimes thought that Null Objects are over simple and quot;stupidquot; but in truth a Null Object always knows exactly what needs to be done without interacting with any other objects. So in truth it is very quot;smart.quot; * This patterns was originally written up by Bobby Wolf, in Pattern Languages of Program Design 3
  • 3. 252 Design Patterns Course Applicability Use the Null Object pattern when: an object requires a collaborator. The Null Object pattern does not introduce this collaboration-- it makes use of a collaboration that already exists. some collaborator instances should do nothing. you want to abstract the handling of null away from the client. Participants Client o requires a collaborator. AbstractObject o declares the interface for Client's collaborator. o implements default behavior for the interface common to all classes, as appropriate. RealObject o defines a concrete subclass of AbstractObject whose instances o provide useful behavior that Client expects. NullObject o provides an interface identical to AbstractObject's so that a null object can be substituted for a real object. o implements its interface to do nothing. What exactly it means to do nothing depends on what sort of behavior Client is expecting. o when there is more than one way to do nothing, more than one NullObject class may be required. Collaborations Clients use the AbstractObject class interface to interact with their collaborators. If the receiver is a RealObject, then the request is handled to provide real behavior. If the receiver is a NullObject, the request is handled by doing nothing or at least providing a null result. Consequences The Null Object pattern: defines class hierarchies consisting of real objects and null objects. Null objects can be used in place of real objects when the object is expected to do nothing. Whenever client code expects a real object, it can also take a null object. makes client code simple. Clients can treat real collaborators and null collaborators uniformly. Clients normally don't know (and shouldn't care) whether they're dealing with a real or a null collaborator. This simplifies client code, because it avoids having to write testing code which handles the null collaborator specially. encapsulates the do nothing code into the null object. The do nothing code is easy to find. Its variation with the AbstractObject and RealObject classes is readily apparent. It can be efficiently
  • 4. Null Object 253 coded to do nothing. It does not require variables that contain null values because those values can be hard-coded as constants or the do nothing code can avoid using those values altogether. makes the do nothing code in the null object easy to reuse. Multiple clients which all need their collaborators to do nothing will all do nothing the same way. If the do nothing behavior needs to be modified, the code can be changed in one place. Thereafter, all clients will continue to use the same do nothing behavior, which is now the modified do nothing behavior. makes the do nothing behavior difficult to distribute or mix into the real behavior of several collaborating objects. The same do nothing behavior cannot easily be added to several classes unless those classes all delegate the behavior to a class which can be a null object class. can necessitate creating a new NullObject class for every new AbstractObject class. can be difficult to implement if various clients do not agree on how the null object should do nothing as when your AbstractObject interface is not well defined. always acts as a do nothing object. The Null Object does not transform into a Real Object. Figure 87 - Before and After - Null Object pattern gets rif of quot;ifquot; statements
  • 5. 254 Design Patterns Course Implementation There are several issues to consider when implementing the Null Object pattern: 1. Null Object as Singleton. The Null Object class is often implemented as a Singleton [GHJV95, page 127]. Since a null object usually does not have any state, its state can't change, so multiple instances are identical. Rather than use multiple identical instances, the system can just use a single instance repeatedly. 2. Clients don't agree on null behavior. If some clients expect the null object to do nothing one way and some another, multiple NullObject classes will be required. If the do nothing behavior must be customized at run time, the NullObject class will require pluggable variables so that the client can specify how the null object should do nothing (see the discussion of pluggable adaptors in the Adapter pattern [GHJV95, page 142]). This may generally be a symptom of the AbstractObject not having a well defined (semantic) interface. 3. Transformation to Real Object. A Null Object does not transform to become a Real Object. If the object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null object. It may be a real object with a do nothing mode, such as a controller which can switch in and out of read-only mode. If it is a single object which must mutate from a do nothing object to a real one, it should be implemented with the State pattern [GHJV95, page 305] or perhaps the Proxy pattern [GHJV95, page 207]. In this case a Null State may be used or the proxy may hold a Null Object. 4. Null Object is not Proxy. The use of a null object can be similar to that of a Proxy [GHJV95, page 207], but the two patterns have different purposes. A proxy provides a level of indirection when accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting like a real subject. A null object will not mutate to start providing real behavior, it will always provide do nothing behavior. 5. Null Object as special Strategy. A Null Object can be a special case of the Strategy pattern [GHJV95, page 315]. Strategy specifies several ConcreteStrategy classes as different approaches for accomplishing a task. If one of those approaches is to consistently do nothing, that ConcreteStrategy is a NullObject. For example, a Controller is a View's Strategy for handling input, and NoController is the Strategy that ignores all input. 6. Null Object as special State. A Null Object can be a special case of the State pattern [GHJV95, page 305]. Normally, each ConcreteState has some do nothing methods because they're not appropriate for that state. In fact, a given method is often implemented to do something useful in most states but to do nothing in at least one state. If a particular ConcreteState implements most of its methods to do nothing or at least give null results, it becomes a do nothing state and as such is a null state. [Woolf96] 7. Null Object as Visitor host. A Null Object can be used to allow a Visitor [GHJV95, page 331] to safely visit a hierarchy and handle the null situation.
  • 6. Null Object 255 8. The Null Object class is not a mixin. Null Object is a concrete collaborator class that acts as the collaborator for a client which needs one. The null behavior is not designed to be mixed into an object that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of the behavior that may or may not be do nothing behavior. [Woolf96] Figure 88 - Using Null Object pattern for Mocking Databases Andy Tips: A Null Object provides a surrogate for another object that shares the same interface, but does nothing. Thus the Null Object encapsulates the implementation decisions of how to do nothing and hides those details from its collaborators.
  • 7. 256 Design Patterns Course Code: Without Null Object from time import asctime, localtime class RealLogging: def Log(self, msg): print 'Logged at', asctime(localtime()), msg # Proxy / wrapper around either null or real logger. class Logger: def __init__(self): self.logger = RealLogging() def Log(self, msg): if self.logger: self.logger.Log(msg) def On(self): self.logger = RealLogging() def Off(self): self.logger = None Logger = Logger() # Usage: class API: def doA(self): if Logger.logger: Logger.Log('Am calling A') print 'A done.' def doB(self): if Logger.logger: Logger.Log('Am calling B') print 'B done.' o = API() o.doA() o.doB()
  • 8. Null Object 257 Logger.Off() o.doA() o.doB() With Null Object # Null Object Pattern class AbstractLogging: def Log(self, msg): pass from time import asctime, localtime class RealLogging(AbstractObject): def Log(self, msg): print 'Logged at', asctime(localtime()), msg class NullLogging(AbstractObject): def Log(self, msg): return # Proxy / wrapper around either null or real logger. class Logger: def __init__(self): self.On() def Log(self, msg): self.logger.Log(msg) def On(self): self.logger = RealLogging() def Off(self): self.logger = NullLogging() Logger = Logger() # Usage: class API: def doA(self): Logger.Log('Am calling A') print 'A done.' def doB(self): Logger.Log('Am calling B') print 'B done.' o = API() o.doA()
  • 9. 258 Design Patterns Course o.doB() Logger.Off() o.doA() o.doB() Notice – no more “if” statements in the client code (API class). Notes: