[Tutor] Null Object Design Pattern Question

Francis Moore Francis.Moore at shaws.co.uk
Mon Jun 14 05:20:36 EDT 2004


> From: Tim Johnson [mailto:tim at johnsons-web.com] 

> which has an example of using a Null() object.
> Unfortunately, I'm having a problem wrapping my brain 
> around the usefulness of this object compared to just using None.

Tim,

I've never used a Null Object pattern (NOP) in Python but I've used it 
quite a few times in C++. The NOP is primarily handy for removing lots
of 
conditional code. For instance, imagine a program where we have an
option 
to log user output. We should then allow the user to switch logging on
or 
off (to speed up the program). So, in our program we would normally need
to 
use lots of conditional code to see whether logging is turned off or 
not i.e.

if logging_on:
    Logger.Log(message)
elif:
    pass

etc...

An easier way is to code a base class called Logger and two concrete
classes 
derived from Logger called RealLogger and NullLogger (an instance of the
NOP). 
At the beginning of the program we create an instance of the correct
class 
(RealLogger or NullLogger) depending on whether the user has logging
switched 
on or not and bind it to an instance of the Logger class. We can then 
use the objects polymorphically, by just calling Logger.Log(message) and
the 
correct class will be called. 
There is now no need to write conditional code and check against None. 
The correct object does the right thing. The RealLogger logs all
messages, the 
NullLogger lets the message pass through. Using the same line of code.

If logging is widespread throughout your application this can provide a
huge 
reduction in the number of lines and make the application logic clearer.

Hope this helps,
Francis. 
  
CONFIDENTIALITY NOTICE 
This communication contains information which is confidential and may also be privileged. It is for the exclusive use of the intended recipient(s). If you are not the intended recipient(s) please note that any distribution, copying or use of this communication or the information in it is strictly prohibited. If you have received this communication in error please notify us by e-mail or by telephone (+44(0) 1322 621100) and then delete the e-mail and any copies of it.  
This communication is from Shaw & Sons Limited whose registered office is at Shaway House, 21 Bourne Park, Bourne Road, Crayford, Kent DA1 4BZ. The views expressed in this communication may not be the views held by Shaw & Sons Limited. 
This message has been checked for all known viruses by McAfee VirusScan. 
 



More information about the Tutor mailing list