Null Object
Null Object
Something for Nothing
Kevlin Henney
March 2003
Kevlin@curbralan.com
Kevlin@acm.org
[Abstract]
Abstract
NULL OBJECT intention is to provide a substitute for the provision of appropriate and do nothing default behavior of those who object to package the object does not exist. In short, is to provide a "nothing will come of nothing" [Shakespeare1605] design patterns.
NULL OBJECT is a long time been repeatedly explored a very clever design, and it is not also use object-oriented (object-oriented) system, also used to drive to empty file (Unix System / dev / null, as well as Microsoft System of NUL), and so on.
The pattern has been documented in a variety of forms by many authors, varying widely in
Structure and length: from a thorough and structured GOF-like form [Woolf1998] to a brief
Thumbnail-like production-rule form [Henney1997]. This paper is derived from a
Previously published article [Henney1999] and includes the aforementioned thumbnail.
The aim of the current work is to update and capture the latest understanding of the
Pattern and its implications, also addressing a wide audience by documenting the pattern
Primarily with respect to Java and UML.
Thumbnail
If
One object may be invoked for air
; This must be invoked at every check whether the use of air
; Empty object results not do anything or allocation of an appropriate default values
Then
Providing a target derived from the application of this type of class
; To achieve all of its methods and to make these methods do nothing or to provide a default results
When the object may be invoked for air, the use of this instance of the class
[Question]
Problem
Given subject may be used for air, and if the test results cited for air, and then not do anything or use some of the default values. However, how to make this object does not exist - there may be the target of air quote - was obvious use?
[Model]
Example
Consider a simple service services provide a simple log. It may be used as a record of the abnormal events, as well as management of records in the course of day-to-day operation of the results. You may imagine many different types of logs, for example, the output directly to the console log or use of RMI (Remote Method Invocation (remote method call)) information will be sent to the remote server log. However, we must not use a server log, and log server, a link between arbitrary. [Figure 1] showed that in UML Class Diagram of the relationship between the [Listing 1] Log shows a simple interface and the realization of the two.
Figure 1. A service log UML Class Diagram
Public interface Log
(
Void write (String messageToLog);
)
Public class ConsoleLog implements Log
(
Public void write (String messageToLog)
(
System.out.println (messageToLog);
)
)
? Interface?
Public class FileLog implements Log
(
Public FileLog (String logFileName)
(
Try
(
Out = new FileWriter (logFileName, true);
)
Catch (IOException caught)
(
Throw new RuntimeException ( "Failed to open log file:" + caught);
)
)
Public void write (String messageToLog)
(
Try
(
Out.write ( "[" + new Date () + ":" + messageToLog + "\ n");
Out.flush ();
)
Catch (IOException caught)
(
Throw new RuntimeException ( "Failed to write to log:" + caught);
)
)
Private final FileWriter out;
)
[Listing 1] Log a simple interface and the realization of the two
In Listing 2], we can see that each object in the use of Log prior to repeatedly check whether empty - Null.
Public class Service
(
Public Service ()
(
This (null);
)
Public Service (Log log)
(
This.log = log;
… / / Other initialization
)
Public Result handle (Request request)
(
If (log! = Null)
Log.write (the "Request" request + + "received");
…
If (log! = Null)
Log.write (the "Request" request + + "handled");
…
)
… / / Other methods and fields
Private Log log;
)
[Listing 2] I in the service initialization, the use of log object
[Strength]
Forces
This is a procedure similar to the
If (log! = Null)
Log.write (message);
Good code a solution!
This type of code duplication and tend to make mistakes: whether the repeated inspections Null cited for code makes very confusing and unclear; also very easy to forget to write Null cited test. However, users need to aware of this situation and to take appropriate idleness, although such a situation does not exist in any case. But with an empty log [Null] is the target we are looking forward to the state. This allows the use of log objects become very simple and uniform.
If (log! = Null)
Log.write (message);
Use a clear conditions, which means that users can be achieved by specific circumstances to select Options. However, if the operator is usually the same, or this kind of choice relations were frequent use. Code duplication thought to be a "bad taste." "Bad smell" [Fowler1999] These copies are usually the work of only a few different parts, such as the consolidation and improvement, as well as a violation of the DRY principle [(Don't Repeat Yourself) [Hunt +2000]].
The space used in the implementation of the external conditions on the quantity of consumption is not more than tests or branches, on the other hand, the use of external testing, detection means that we must have been detected, because such detection in separate code was constantly repeat, The compiler can set breakpoints on diagnosis or compile statements.
Air detection if [null] can be ignored or hidden, the code will become more clear! JVM has been visited by every object used to prevent object reference is empty, this may be the use of this technology are a temptation it. (See [Listing 3]), the technology used by the specific language requirements, it is essential to ensure that all the targets were to have been tested. For example: Java and C #. When there is no guarantee this will not lead to the need (not clear) results. For example: C + +.
Public class Service
(
…
Public Result handle (Request request)
(
Try
(
Log.write (the "Request" request + + "received");
…
Log.write (the "Request" request + + "handled");
…
)
Catch (NullPointerException ignored)
(
)
)
…
)
Listing 3. Assuming a non-null log and ignoring any NullPointerException.
This relies on two flaws in the language.
; Style: Despite general recommendations "should be special exceptions," [ "exceptions should be exceptional"] ambiguity, which is not like the record to shield those NullPointerException dependence on a clear abuse of empty platitudes not doing. Adoption of such a style as a normal dynamic performance-optimization; such reasoning does not apply cited 3.
; Correctness: NullPointerException for access through any empty row voted, and not only through the wood to write. Ignore such an exception operation repeal real mistake, throwing the baby with the bath water out the obvious dangers. Check in the air firms oppose catch uglifies code provisions beyond the timber, and on any occasion still do not provide a guarantee that the timber is an invalid prisoners. A solution was needed by the left is to hope that the ability of air to nothing - not special things - happen. Such a solution should be in the run-time non-invasive, easier coding, and cheap.
[Solution]
Solution
Provide something for nothing: a class, the need to refer to the object interface, and to achieve all of its methods, and these methods do not do anything or to the appropriate default values. May be invoked when the object is empty, the use of this instance of the class. Figure 2 shows a basic, typical NULL OBJECT.
NULL OBJECT can be completely normal in many model or object structures: an empty TERATOR [Gamma +1995] not see any place an empty COMMAND [Gamma +1995] do (or not do) anything in the C language, it can be by providing a space at the function pointer to achieve an empty callback; an empty pool can not be changed; an empty STRATEGY [Gamma +1995] does not provide any algorithm behavior.
NULL OBJECT can not be used as an alternative to air quote. Its purpose is to package some of the object does not exist, where a wrong that is not the actual user objects deep important. If the selectivity of the basic means to lead to different behavior, NULL OBJECT inappropriate. Any type of a run-time needs, such as a isNull method that is not important and not transparent, and recommendations for the space [NULL] rather than a NULL OBJECT.
For example, an image editor, an empty [NULL] colors, resulting in transparent colors, which will be NULL OBJECT good application. However, the unmarried state is not the best description of the spouse with an empty object together: marriage is a choice, and as a single really different.
For example, in a graphical editor, a null fill color leads to transparency and would be a
Good use of a NULL OBJECT. However, the state of being unmarried is not best represented
With a null spouse object: marriage is optional, and being single really is different.
[Solution]
Resolution
Return to the example of this log, a NULL OBJECT categories - NullLog, LOG level can be introduced, such as an empty category [null class] (see Listing 4) do nothing and does not require a lot of coding skills! !
Public class NullLog implements Log
(
Public void write (String messageToLog)
(
)
)
Listing 4. An empty Log category, with an empty act
NULL OBJECT advantages: Once initialized, it can be very easy to use this simple log framework. Log can now be assured of a target is mandatory, that is, log service is diversity. This was to strengthen the relationship between the code to allow clear conditions are eliminated, records simpler and more uniform. Polymorphism in the responsibility of the choices so that the records of the existence of transparent (or not) (see list 5).
Public class Service
(
Public Service ()
(
This (new NullLog ());
)
Public Service (Log log)
(
This.log = log;
…
)
Public Result handle (Request request)
(
Log.write (the "Request" request + + "received");
…
Log.write (the "Request" request + + "handled");
…
)
…
Private Log log;
)
Listing 5. Introducing a NullLog object into Service.
[Figure 3] showed that the design of the interface (based on Listing 4, Listing 5 and Figure 1), as well as between them is how to coordinate various parts of the role
Figure 2 of the general.
Figure 3. The relationship between the problem resolution and the roles described in Figure 2.
[Deduction]
Consequences
NULL OBJECT introduced through the elimination of duplication and excessive non-core-logic method to simplify the customer part of the code. Choose and change is the culmination of many state and the inheritance of this process than the conditions better than testing. Even so, many states can switch away from the statement or if else if the
Nested to performance. NULL OBJECT in this special category, virtual (but hidden) default or air has been trapped or hidden.
Object relations from the option to mandatory, which makes the relationship between the use of more unity. However, in order to preserve the fixed amount, it is necessary to
Ensure that the quote should not be regarded as empty:
; Object may be invoked final clearance, only the object initialization cited the need to examine the object, NULL OBJECT installed in this position.
; Two optional one, only INDIRECT VARIABLE ACCESS [Beck1997] was used to access the object. SETTING METHOD [Beck1997] can be used to ensure that the allocation of a NULL OBJECT rather than an empty quoted; GETTING METHOD [Beck1997] can be used to ensure that an empty return to a NULL OBJECT.
NULL OBJECT is Packaging and cohesion: it do one thing - do nothing - it has done well. It makes acts (non-existent) easier to use, and provide an appropriate location to build breakpoints or print statements.
A NULL OBJECT is encapsulated and cohesive: It does one thing - nothing - and it does it
Well. This reification of the void and encapsulation of emptiness eliminates duplicate
Coding, makes the (absence of) behavior easier to use, and provides a suitable venue for
Debug breakpoints or print statements.
NULL OBJECT a copy of the non-existence of any means that it is an example of change and therefore can be shared and the security thread is the essence. A NULL OBJECT typical characteristics is that it does not regional, which means that all the examples is the same, identical. If a certain period of time or space needs of a single static instance, you can use SINGLETON object [Gamma +1995].
On the other hand, the relationship between the use of a NULL OBJECT mean that the method of operation was always called, but their arguments will always be evaluated. For normal circumstances this is not an issue, but there will always be a way to confirm the recurrent expenditure Method Invocation whose arguments assessment is a complex and expensive.
Do not rely on the use of NULL OBJECT hierarchy decided to go to remote object. If a Java-NULL OBJECT realized java.rmi.Remote interface, each method of long-distance calls would lead to huge costs and the call is a potential recipe for failure, the two will be submerged and gradually destroy it basically do nothing behaviour . Therefore, if in the context of the distribution of the use of NULL OBJECT, priority should be given choice transfer null value, it will be a copy of the use of NULL OBJECT. Distribution of the environment in a transparent answer is not transparent sharing a priority. RMI because of the introduction of a major capital expenditure, because of a NULL OBJECT type is small and will be included in it is relatively cheap. The only change in the code is to achieve java.io.Serializable interface NULL OBJECT:
Public class NullLog implements Log, Serializable
(
…
)
There are many other ways to carry out doing nothing, can bring more NULL OBJECT category. If EXCEPTIONAL VALUE object can be used [Cunningham1995]. With doing nothing different, when a method is invoked, EXCEPTIONAL VALUE will trigger an abnormal or return a EXCEPTIONAL VALUE.; SPECIAL CASE [Fowler2003] - When an object in a particular state or situation, such as EXCEPTIONAL VALUE or NULL OBJECT, do nothing to achieve is very simple! However, the mode of transmission of different parameters requires a different response:
Because the
Null Object
10 of 10
Subclass does not truly conform to the superclass, failing the is a or is a kind of litmus test
For appropriate use of inheritance. The inclusion of redundant implementation that cannot
Be disinherited suggests a tradeoff with weaker cohesion. However, the inheritance from an
Existing concrete class cannot be used if it or any of its methods are declared final.
Note that, for the same reasons of substitutability, a NULL OBJECT class should not be used
As a superclass except for other NULL OBJECT classes. The assumption is that any
Inheritance of a NULL OBJECT class will preserve that classification - the subclass of a
NULL OBJECT class is also a NULL OBJECT class, and its instances can be used where any
NULL OBJECT is expected.
Acknowledgments
An earlier version of this paper was published in Java Report (RIP) [Henney1999]. The
Current version has also benefited from earlier papers by Bruce Anderson [Anderson1996]
And Bobby Woolf [Woolf1998].
I would like to thank the following people: Joe Bergin for his shepherding and humor;
Hubert Matthews for his additional comments on the preshepherded version of this paper;
Frank Buschmann and the Siemens patterns retreat in St Martin, Austria, in June 2000 for
Their company and comments on a previous draft of this paper; Jim Coplien, Pascal
Costanza, Jutta Eckstein, Ian Graham, Klaus Marquardt, Alan O'Callaghan, Andreas
Rüping, Titos Saridakis, Didi Schütz, Christa Schwanninger, Markus V? Lter, and Uwe
Zdun for the comments they gave on the paper at EuroPLoP 2002.
References
[Anderson1996] Bruce Anderson, "Null Object," PloP'96.
[Beck1997] Kent Beck, Smalltalk Best Practice Patterns, Prentice Hall, 1997.
[Buschmann +1996] Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad,
And Michael Stal, Pattern-Oriented Software Architecture, Volume 1: A System of Patterns,
Wiley, 1996.
[Cunningham1995] Ward Cunningham, "The CHECKS Pattern Language of Information
Integrity, "Pattern Languages of Program Design, edited by James O Coplien and Douglas
C Schmidt, Addison-Wesley, 1995.
[Fowler1999] Martin Fowler, Refactoring: Improving the Design of Existing Code, Addison -
Wesley, 1999.
[Fowler2003] Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley,
1999.
[Gamma +1995] Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Design
Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1995.
[Henney1997] Kevlin Henney, "Java Patterns and Implementations," presented at BCS
OOPS Patterns Day, October 1997, http://www.curbralan.com.
[Henney1999] Kevlin Henney, "Patterns in Java: Something for Nothing", Java Report 4 (12),
December 1999, http://www.curbralan.com.
[Hunt +2000] Andrew Hunt and David Thomas, The Pragmatic Programmer, Addison -
Wesley 2000.
[Schmidt +2000] Douglas Schmidt, Michael Stal, Hans Rohnert, and Frank Buschmann,
Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked
Objects, Wiley, 2000.
[Shakespeare1605] William Shakespeare, King Lear, 1605.
[Woolf1998] Bobby Woolf, "Null Object" Pattern Languages of Program Design 3, edited by
Robert Martin, Dirk Riehle, and Frank Buschmann, Addison-Wesley, 1998.
Tags: object








0 Comments to “Null Object”
No Comments. Send your comment.
Leave a Reply
You must be logged in to post a comment.