SlideShare a Scribd company logo
1 of 9
Download to read offline
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:

More Related Content

What's hot

Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)Fahad Golra
 
Location-Based Services on Android
Location-Based Services on AndroidLocation-Based Services on Android
Location-Based Services on AndroidJomar Tigcal
 
Village scenery graphics C programming
Village scenery graphics C programmingVillage scenery graphics C programming
Village scenery graphics C programmingPrionto Abdullah
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Distributed sagas a protocol for coordinating microservices
Distributed sagas a protocol for coordinating microservicesDistributed sagas a protocol for coordinating microservices
Distributed sagas a protocol for coordinating microservicesJ On The Beach
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
Reactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみた
Reactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみたReactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみた
Reactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみたAkihiro Kitada
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 

What's hot (20)

GraphQL Security
GraphQL SecurityGraphQL Security
GraphQL Security
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
Location-Based Services on Android
Location-Based Services on AndroidLocation-Based Services on Android
Location-Based Services on Android
 
Village scenery graphics C programming
Village scenery graphics C programmingVillage scenery graphics C programming
Village scenery graphics C programming
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Distributed sagas a protocol for coordinating microservices
Distributed sagas a protocol for coordinating microservicesDistributed sagas a protocol for coordinating microservices
Distributed sagas a protocol for coordinating microservices
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Files in java
Files in javaFiles in java
Files in java
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Reactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみた
Reactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみたReactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみた
Reactive Streams に基づく非同期処理プログラミング 〜 Reactor を使ってみた
 
Music on cloud
Music on cloudMusic on cloud
Music on cloud
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Android Services
Android ServicesAndroid Services
Android Services
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 

Viewers also liked

The Null Object Pattern
The Null Object PatternThe Null Object Pattern
The Null Object Patternmodern_legend
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael Heron
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 

Viewers also liked (8)

The Null Object Pattern
The Null Object PatternThe Null Object Pattern
The Null Object Pattern
 
Null object pattern
Null object patternNull object pattern
Null object pattern
 
design patterns java
design patterns javadesign patterns java
design patterns java
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 

Similar to Null Object Design Pattern

Something for Nothing
Something for NothingSomething for Nothing
Something for NothingKevlin Henney
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Javascript Object Patterns.pptx
Javascript Object Patterns.pptxJavascript Object Patterns.pptx
Javascript Object Patterns.pptxAlaref Abushaala
 
AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere Miklos Csere
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar Ali
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaGaddafiAdamu1
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design PatternsRobert Brown
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Inverting Dependencies
Inverting DependenciesInverting Dependencies
Inverting DependenciesLuc Trudeau
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with javaRajiv Gupta
 

Similar to Null Object Design Pattern (20)

Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Design Patterns in Ruby
Design Patterns in RubyDesign Patterns in Ruby
Design Patterns in Ruby
 
Abstract
AbstractAbstract
Abstract
 
Javascript Object Patterns.pptx
Javascript Object Patterns.pptxJavascript Object Patterns.pptx
Javascript Object Patterns.pptx
 
AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Agile cards
Agile cardsAgile cards
Agile cards
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
Automate Design Patterns
Automate Design PatternsAutomate Design Patterns
Automate Design Patterns
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design Patterns
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Sda 8
Sda   8Sda   8
Sda 8
 
Inverting Dependencies
Inverting DependenciesInverting Dependencies
Inverting Dependencies
 
C#/.NET Little Pitfalls
C#/.NET Little PitfallsC#/.NET Little Pitfalls
C#/.NET Little Pitfalls
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 

More from tcab22

State Pattern In Flex
State Pattern In FlexState Pattern In Flex
State Pattern In Flextcab22
 
Blackboard Pattern
Blackboard PatternBlackboard Pattern
Blackboard Patterntcab22
 
Tooled Composite Design Pattern
Tooled Composite Design PatternTooled Composite Design Pattern
Tooled Composite Design Patterntcab22
 
Tooled Composite Design Pattern presentation
Tooled Composite Design Pattern presentationTooled Composite Design Pattern presentation
Tooled Composite Design Pattern presentationtcab22
 
Andy Bulka Pattern Automation
Andy Bulka Pattern AutomationAndy Bulka Pattern Automation
Andy Bulka Pattern Automationtcab22
 
Representing Design Patterns In Uml Andy Bulka Oct2006
Representing Design Patterns In Uml Andy Bulka Oct2006Representing Design Patterns In Uml Andy Bulka Oct2006
Representing Design Patterns In Uml Andy Bulka Oct2006tcab22
 

More from tcab22 (6)

State Pattern In Flex
State Pattern In FlexState Pattern In Flex
State Pattern In Flex
 
Blackboard Pattern
Blackboard PatternBlackboard Pattern
Blackboard Pattern
 
Tooled Composite Design Pattern
Tooled Composite Design PatternTooled Composite Design Pattern
Tooled Composite Design Pattern
 
Tooled Composite Design Pattern presentation
Tooled Composite Design Pattern presentationTooled Composite Design Pattern presentation
Tooled Composite Design Pattern presentation
 
Andy Bulka Pattern Automation
Andy Bulka Pattern AutomationAndy Bulka Pattern Automation
Andy Bulka Pattern Automation
 
Representing Design Patterns In Uml Andy Bulka Oct2006
Representing Design Patterns In Uml Andy Bulka Oct2006Representing Design Patterns In Uml Andy Bulka Oct2006
Representing Design Patterns In Uml Andy Bulka Oct2006
 

Recently uploaded

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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: