The intent of a Null Object is to encapsulate the absense of an object by providing a substitutable alternative that offers suitable default do nothing behavior.
- An object reference may be optionally null and
- This reference must be checked before every use and
- The result of a null check is to do nothing or assign a suitable default value.
if(log!=null){log.Write(request);}// more statementsif(log!=null){log.Write(request);}- Provide a class derived from the object reference's type and
- Implement all its methods to do nothing or provide default results and
- Use an instance of this class whenever the object reference would have been null
Definition
interfaceILog{voidWrite(stringmessage);}classNullLog:ILog{publicvoidWrite(stringmessage){// do nothing}}Usage
ILoglog=newNullLog();// somewhere laterlog.Write(request);log?.Write(request);Null-Object cannot be used for Immutable classes (eg. String).
