Posts

Showing posts from May, 2016

Null Object Pattern

Image
Null Object Pattern Motivation The Null Object pattern can be used to avoid having checks that objects are not null before using them to avoid throwing NullReferenceExceptions, e.g. if (myObject == null) {    return; } // do something with myObject… Example For example, say we have a device object with a Connect() method that a client wishes to call. If we're getting the device from a repository we have to do a check for null before calling Connect(). If however the repository returns the null object, no null check is required. The null check is done within the repository so the client code does have to worry about it. Null object code public interface IDevice     {         string Name { get ; set ; }         void Connect ();     }     public class RealDevice : IDevice     {         public string Name { get ; set ; }         public void Connect ()         {             Console .WriteLine( "Device i