Design patterns and practices in .NET: the Template Method design pattern

Introduction

The Template Method pattern is best used when you have an algorithm consisting of certain steps and you want to allow for different implementations of these steps. The implementation details of each step can vary but the structure and order of the steps are enforced.

A good example is games:

  1. Set up the game
  2. Take turns
  3. Game is over
  4. Display the winner

A large number of games can implement this algorithm, such as Monopoly, Chess, card games etc. Each game is set up and played in a different way but they follow the same order.

The Template pattern is very much based around inheritance. The algorithm represents an abstraction and the concrete game types are the implementations, i.e. the subclasses of that abstraction. It is of course plausible that some steps in the algorithm will be implemented in the abstraction while the others will be overridden in the implementing classes.

Note that a prerequisite for this pattern to be applied properly is the rigidness of the algorithm steps. The steps must be known and well defined. The pattern relies on inheritance, rather than composition, and merging two child algorithms into one can prove difficult. If you find that the Template pattern is too limiting in your application then consider the Strategy or the Decorator patterns.

This pattern helps to implement the so-called Hollywood principle: Don’t call us, we’ll call you. It means that high level components, i.e. the superclasses, should not depend on low-level ones, i.e. the implementing subclasses. A base class with a template method is a high level component and clients should depend on this class. The base class will include one or more template method that the subclasses implement, i.e. it is the base class calling the implementation and not vice versa. In other words, the Hollywood principle is applied from the point of view of the base classes: dear implementing classes, don’t call us, we’ll call you.

Demo

Open Visual Studio and create a new blank solution. We’ll simulate a simple dispatch service where shipping an item must go through specific steps regardless of which specific service completes the shipment. Insert a new Console application to the solution.

We’ll start with the most important component of the pattern: the base class that must be respected by each implementation. Add a class called OrderShipment:

public abstract class OrderShipment
    {
        public string ShippingAddress { get; set; }
        public string Label { get; set; }
        public void Ship(TextWriter writer)
        {
            VerifyShippingData();
            GetShippingLabelFromCarrier();
            PrintLabel(writer);
        }

        public virtual void VerifyShippingData()
        {
            if (String.IsNullOrEmpty(ShippingAddress))
            {
                throw new ApplicationException("Invalid address.");
            }
        }
        public abstract void GetShippingLabelFromCarrier();
        public virtual void PrintLabel(TextWriter writer)
        {
            writer.Write(Label);
        }
    }

The template method that implements the order of the steps is Ship. It calls three methods in a specific order. Two of them – VerifyShippingData and PrintLabel are virtual and have a default implementation. They can of course be overridden. The third method, i.e. GetShippingLabelFromCarrier is the abstract method that the base class cannot implement. The superclass has no way of knowing what a service-specific shipping label looks like – it is delegated to the implementations. We’ll simulate two services, UPS and FedEx:

public class FedExOrderShipment : OrderShipment
	{
		public override void GetShippingLabelFromCarrier()
		{
			// Call FedEx Web Service
			Label = String.Format("FedEx:[{0}]", ShippingAddress);
		}
	}
public class UpsOrderShipment : OrderShipment
	{
		public override void GetShippingLabelFromCarrier()
		{
			// Call UPS Web Service
			Label = String.Format("UPS:[{0}]", ShippingAddress);
		}
	}

The implementations should be quite straighforward: they create service-specific shipping labels and set those values to the Label property. There’s of course nothing stopping the concrete classes from overriding any other step in the algorithm. Adding new shipping services is very easy: just create a new implementation. Let’s see how a client would communicate with the services:

static void Main(string[] args)
{
	OrderShipment service = new UpsOrderShipment();
	service.ShippingAddress = "New York";
	service.Ship(Console.Out);

	OrderShipment serviceTwo = new FedExOrderShipment();
	serviceTwo.ShippingAddress = "Los Angeles";
	serviceTwo.Ship(Console.Out);
        
        Console.ReadKey();
}

Run the programme and you’ll see the service-specific labels in the Console. The client calls the Template method Ship which ensures that the steps in the shipping algorithm are carried out in a certain order.

It is of course not optimal to create the specific OrderShipment classes like that, i.e. directly with the new keyword as it introduces tight coupling. Consider using a factory for building the correct implementation. However, this solution is satisfactory for demo purposes.

View the list of posts on Architecture and Patterns here.

Design patterns and practices in .NET: the State pattern

Introduction

The State design pattern allows to change the behaviour of a method through the state of an object. A typical scenario where the state pattern is used when an object goes through different phases. An issue in a bug tracking application can have the following states: inserted, reviewed, rejected, processing, resolved and possibly many others. Depending on the state of the bug the behaviour of the underlying system may also change: some methods will become (un)available and some of them will change their behaviour. You may have seen or even produced code similar to this:

public void ProcessBug()
{
	switch (state)
	{
		case "Inserted":
			//call another method based on the current state
			break;
		case "Reviewed":
			//call another method based on the current state
			break;
		case "Rejected":
			//call another method based on the current state
			break;
		case "Resolved":
			//call another method based on the current state
			break;
	}
}

Here we change the behaviour of the ProcessBug() method based on the state of the “state” parameter, which represents the state of the bug. You can imagine that once a bug has reached the Rejected status then it cannot be Reviewed any more. Also, once it has been reviewed, it cannot be deleted. There are other similar scenarios like that where the available actions and paths depend on the actual state of an object.

Suppose you have public methods to perform certain operations on an object: Insert, Delete, Edit, Resolve, Reject. If you follow the above solution then you will have to insert a switch statement in each and check the actual state of the object and act accordingly. This is clearly not maintainable; it’s easy to get lost in the chain of the logic, it gets difficult to update the code if the rules change and the class code grows unreasonably large compared to the amount of logic carried out.

There are other issues with the naive switch-statement approach:

  • The states are hard coded which offers no or little extensibility
  • If we introduce a new state we have to extend every single switch statement to account for it
  • All actions for a particular state are spread around the actions: a change in one state action may have an effect on the other states
  • Difficult to unit test: each method can have a switch statement creating many permutations of the inputs and the corresponding outputs

In the switch statement solution the states are relegated to simple string properties. In reality they are more likely to be more important objects that are part of the core Domain. Hence that logic should be encapsulated into separate objects that can be tested independently of the other concrete state types.

Demo

We’ll simulate an e-commerce application where an order can go through the following states: New, Shipped, Cancelled. The rules are simple: a new order can be shipped or cancelled. Shipped and cancelled orders cannot be shipped or cancelled again.

Fire up Visual Studio and create a blank solution. Insert a Windows class library called Domains. You can delete Class1.cs. The first item we’ll insert is a simple enumeration:

public enum OrderStatus
	{
		New
		, Shipped
		, Cancelled
	}

Next we’ll insert the interface that each State will need to implement, IOrderState:

public interface IOrderState
	{
		bool CanShip(Order order);
		void Ship(Order order);
		bool CanCancel(Order order);
		void Cancel(Order order);
                OrderStatus Status {get;}
	}

Each concrete state will need to handle these methods independently of the other state types. The Order domain looks like this:

public class Order
	{
		private IOrderState _orderState;

		public Order(IOrderState orderState)
		{
			_orderState = orderState;
		}

		public int Id { get; set; }
		public string Customer { get; set; }
		public DateTime OrderDate { get; set; }
		public OrderStatus Status
		{
			get
			{
				return _orderState.Status;
			}
		}
		public bool CanCancel()
		{
			return _orderState.CanCancel(this);
		}
		public void Cancel()
		{
			if (CanCancel())
				_orderState.Cancel(this);
		}
		public bool CanShip()
		{
			return _orderState.CanShip(this);
		}
		public void Ship()
		{
			if (CanShip())
				_orderState.Ship(this);
		}

		void Change(IOrderState orderState)
		{
			_orderState = orderState;
		}
	}

As you can see each Order related action is delegated to the OrderState object where the Order object is completely oblivious of the actual state. It only sees the interface, i.e. an abstraction, which facilitates loose coupling and enhanced testability.

Let’s implement the Cancelled state first:

public class CancelledState : IOrderState
	{
		public bool CanShip(Order order)
		{
			return false;
		}

		public void Ship(Order order)
		{
			throw new NotImplementedException("Cannot ship, already cancelled.");
		}

		public bool CanCancel(Order order)
		{
			return false;
		}

		public void Cancel(Order order)
		{
			throw new NotImplementedException("Already cancelled.");
		}

		public OrderStatus Status
		{
			get
			{
				return OrderStatus.Cancelled;
			}
		}
	}

This should be easy to follow: we incorporate the cancellation and shipping rules within this concrete state.

ShippedState.cs is also straighyforward:

 
public class ShippedState : IOrderState
	{
		public bool CanShip(Order order)
		{
			return false;
		}

		public void Ship(Order order)
		{
			throw new NotImplementedException("Already shipped.");
		}

		public bool CanCancel(Order order)
		{
			return false;
		}

		public void Cancel(Order order)
		{
			throw new NotImplementedException("Already shipped, cannot cancel.");
		}

		public OrderStatus Status
		{
			get { return OrderStatus.Shipped; }
		}
	}

NewState.cs is somewhat more exciting as we change the state of the order after it has been shipped or cancelled:

 
public class NewState : IOrderState
	{
		public bool CanShip(Order order)
		{
			return true;
		}

		public void Ship(Order order)
		{
			//actual shipping logic ignored, only changing the status
			order.Change(new ShippedState());
		}

		public bool CanCancel(Order order)
		{
			return true;
		}

		public void Cancel(Order order)
		{
			//actual cancellation logic ignored, only changing the status;
			order.Change(new CancelledState());
		}

		public OrderStatus Status
		{
			get { return OrderStatus.New; }
		}
	}

That’s it really, the state pattern is not more complicated than this.

We separated out the state-dependent logic to standalone classes that can be tested independently. It’s now easy to introduce new states later. We won’t have to extend dozens of switch statements – the new state object will handle that logic internally. The Order object is no longer concerned with the concrete state objects – it delegates the cancellation and shipping actions to the states.

View the list of posts on Architecture and Patterns here.

Design patterns and practices in .NET: the Singleton pattern

Introduction

The idea of the singleton pattern is that a certain class should only have one single instance in the application. All other classes that depend on it should all share the same instance instead of a new one. Usually singletons are only created when they are first needed – the same existing instance is returned upon subsequent calls. This is called lazy construction.

The singleton class is responsible for creating the new instance. It also needs to ensure that only this one instance is created and the existing instance is used in subsequent calls.

If you are sure that there should be only one instance of a class then a singleton pattern is certainly a possible solution. Note the following additional rules:

  • The singleton class must be accessible to clients
  • The class should not require parameters for its construction, as input parameters are a sign that multiple different versions of the class are created – this breaks the most important rule, i.e. that “there can be only one”

You may have seen public methods that take the following very simple form:

SingletonClass instance = SingletonClass.GetInstance();

This almost certainly returns a singleton instance. The GetInstance() method is the only way a client can get hold of an instance, i.e. the client cannot call new SingletonClass(). This is due to a private constructor hidden within the SingletonClass implementation.

Basic demo

Open Visual Studio and create a blank solution called Singleton. Add a class library to the solution, remove Class1 and add a class called Singleton to it. The most simple implementation of the singleton pattern looks like this:

public class Singleton
	{
		private static Singleton _instance;

		private Singleton()
		{
		}

		public static Singleton Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new Singleton();
				}
				return _instance;
			}
		}
	}

Inspect the code and you’ll note the following characteristics:

  • The class has a single static instance of itself
  • The constructor is private
  • The object instance is available through the static Instance property
  • The property inspects the state of the private instance; if it’s null then it creates a new instance otherwise just returns the existing one – lazy loading

Note that this implementation is not thread safe, so don’t use this example in case the singleton class is accessed from multiple threads, e.g. in an ASP.NET web application. We’ll see a thread-safe example soon.

It’s perfectly acceptable that the Singleton class has multiple public methods. You can then access those methods as follows:

Singleton.Instance.PerformWork();

Singleton instance = Singleton.Instance;
instance.PerformWork();

//pass as parameter
PerformSomeOtherWork(Singleton.Instance);

Add a new class to the class library called ThreadSafeSingleton with the following implementation:

public class ThreadSafeSingleton
	{
		private ThreadSafeSingleton()
		{
		}

		public static ThreadSafeSingleton Instance
		{
			get { return Nested.instance; }
		}

		private class Nested
		{
			static Nested()
			{
			}

			internal static readonly ThreadSafeSingleton instance = new ThreadSafeSingleton();
		}
	}

This is the construction that is recommended for multithreaded environments, such as web applications. Note that it doesn’t use locks which would slow down the performance. Note the following:

  • As in the previous implementation we have a private constructor
  • We also have a public static property to get hold of the singleton instance
  • The implementation relies on the way type initialisers work in .NET
  • The C# compiler will guarantee that a type initialiser is instantiated lazily if it is not marked with the beforefieldinit flag
  • We can ensure this for the nested class Nested by including a static constructor
  • Apparently there’s no need for the static constructor but it does have an important role for the C# compiler
  • Within the nested class we have a static ThreadSafeSingleton field
  • This field is set to a new ThreadSafeSingleton statically when it’s first referenced
  • That reference only occurs in the Instance property getter which refers to the nested ‘instance’ field
  • The first time the Instance getter is called a new ThreadSafeSingleton class is initialised using the ‘instance’ private field of the nested class
  • Subsequent requests will simply receive the existing instance of this static field
  • This way the “There can be only one” rule is enforced

Drawbacks

Singletons introduce tight coupling between the caller and the singleton making the software design more fragile. Singletons are also very difficult to test and are therefore often regarded as an anti-pattern by fierce advocates of testable code. In addition, singletons violate the ‘S’ in SOLID software design: the Single Responsibility Principle. Managing the object lifetime is not considered the responsibility of a class. This should be performed by a separate class.

However, using an Inversion-of-control (IoC) container we can avoid all of these drawbacks. The demo will show you a possible solution.

Demo

The demo will concentrate on an implementation of the pattern where we eliminate its drawbacks outlined above. This means that you should be somewhat familiar with dependency injection and IoC containers in general. You may have come across IoC containers such as StructureMap before. Even if you haven’t met these concepts before, it may still be worthwhile to read on, you may learn some new things.

The demo application will simulate the simultaneous use of a file for file writes. The solution will make use of the .NET task library to perform file writes in a multithreaded fashion.

For each dependency we’ll need an interface to eliminate the tight coupling mentioned before. Each dependency will be resolved using an IoC container called Unity.

Add a new Console app called FileLoggerAsync to the solution and set it as the startup project. Add the following package reference using NuGet:

Unity package in NuGet

The file writer will simply write a series of numbers to a text file. Add the following interface to the project:

public interface INumberWriter
	{
		void WriteNumbersToFile(int max);
	}

The parameter ‘max’ simply means the upper boundary of the series to save to disk.

We will also need an object that will perform the file writes. This will be our singleton class eventually, but it will be hidden behind an interface:

public interface IFileLogger
	{
		void WriteLineToFile(string value);
		void CloseFile();
	}

We don’t want the client to be concerned with the creation of the file logger so the creation will be delegated to an abstract factory – more on this topic here:

public interface IFileLoggerFactory
	{
		IFileLogger Create();
	}

Not much to comment there I presume.

We’ll first implement the singleton file logger which implements the IFileLogger interface:

public class FileLoggerLazySingleton : IFileLogger
	{
		private readonly TextWriter _logfile;
		private const string filePath = @"c:\logfile.txt";

		private FileLoggerLazySingleton()
		{
			_logfile = GetFileStream();
		}

		public static FileLoggerLazySingleton Instance
		{
			get
			{
				return Nested.instance;
			}
		}
		private class Nested
		{
			static Nested()
			{
			}

			internal static readonly FileLoggerLazySingleton instance = new FileLoggerLazySingleton();
		}

		public void WriteLineToFile(string value)
		{
			_logfile.WriteLine(value);
		}

		public void CloseFile()
		{
			_logfile.Close();
		}

		private TextWriter GetFileStream()
		{
			return TextWriter.Synchronized(File.AppendText(filePath));
		}
	}

You’ll recognise most of the code from the thread-safe singleton implementation shown above. The rest handles writing to a file to the specified file path. It is of course not good practice to hard-code the log file like that, but it’ll do in this example. Feel free to change this value but make sure that the file exists.

Next we’ll implement the IFileLoggerFactory interface:

public class LazySingletonFileLoggerFactory : IFileLoggerFactory
	{
		public IFileLogger Create()
		{
			return FileLoggerLazySingleton.Instance;
		}
	}

It returns the singleton instance of the FileLoggerLazySingleton class. It’s time to implement the INumberWriter interface:

public class AsyncNumberWriter : INumberWriter
	{
		private readonly IFileLoggerFactory _fileLoggerFactory;

		public AsyncNumberWriter(IFileLoggerFactory fileLoggerFactory)
		{
			_fileLoggerFactory = fileLoggerFactory;
		}

		public void WriteNumbersToFile(int max)
		{
			IFileLogger myLogger = null;
			Action<int> logToFile = i =>
			{
				myLogger = _fileLoggerFactory.Create();
				myLogger.WriteLineToFile("Ready for next number...");
				myLogger.WriteLineToFile("Logged number: " + i);
			};
			Parallel.For(0, max, logToFile);
			myLogger.CloseFile();
		}
	}

Let’s see what’s happening here. The class will need a factory to retrieve an instance of IFileLogger – the class will be oblivious to the actual implementation type. Hence we have eliminated the tight coupling problem mentioned above. Then we implement the WriteNumbersToFile method:

  • Initially the IFileLogger object will be null
  • Then we create an inline method using the Action object
  • The Action represents a method which has accepts an integer parameter i
  • In the method body we construct the file logger using the file logger factory
  • Then we write a couple of things to the file

The Action will be used in a parallel loop. The loop is the parallel version of a standard for loop. The variable ‘i’ will not be incremented synchronously but in a parallel fashion. The variable will start at 0 and end with the max value. It is injected into the inline function defined by the Action object. So the method defined in the action object will be run in each loop of the Parallel.For construct. It is important to note that with each iteration the IFileLogger object is created using the IFileLoggerFactory object. Thus we simulate that multiple threads access the same file to write some lines.

Now we’re ready to hook up the individual elements in Program.cs. Let’s first set up the Unity container. Insert the following files to the project:

IoC.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;

namespace FileLogger
{
	public static class IoC
	{
		private static IUnityContainer _container;

		public static void Initialize(IUnityContainer container)
		{
			_container = container;
		}

		public static TBase Resolve<TBase>()
		{
			return _container.Resolve<TBase>();
		}
	}
}

UnityDependencyResolver.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;

namespace FileLogger
{
	public class UnityDependencyResolver
	{
		private static readonly IUnityContainer _container;
		static UnityDependencyResolver()
		{
			_container = new UnityContainer();
			IoC.Initialize(_container);
		}

		public void EnsureDependenciesRegistered()
		{
			_container.RegisterType<IFileLoggerFactory, LazySingletonFileLoggerFactory>();
		}

		public IUnityContainer Container
		{
			get
			{
				return _container;
			}
		}
	}
}

Don’t worry if you don’t understand what’s going on here. The purpose of these classes is to initialise the Unity dependency container and make sure that when Unity encounters a dependency of type IFileLoggerFactory it creates a LazySingletonFileLoggerFactory ready to be injected.

The last missing bit is Program.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;

namespace FileLogger
{
	class Program
	{
		private static UnityDependencyResolver _dependencyResolver;
		private static INumberWriter _numberWriter;

		private static void RegisterTypes()
		{
			_dependencyResolver = new UnityDependencyResolver();
			_dependencyResolver.EnsureDependenciesRegistered();
			_dependencyResolver.Container.RegisterType<INumberWriter, AsyncNumberWriter>();
			
		}

		public static void Main(string[] args)
		{
			RegisterTypes();
			_numberWriter = _dependencyResolver.Container.Resolve<INumberWriter>();
			_numberWriter.WriteNumbersToFile(100);
                        Console.WriteLine("File write done.");
			Console.ReadLine();
		}
	}
}

In RegisterTypes we simply register another dependency: INumberWriter is resolved as the concrete type AsyncNumberWriter. In the Main method we then retrieve the number writer dependency and call its WriteNumbersToFile method. Recall that AsyncNumberWriter will then get hold of the file 100 times in each iteration and write a couple of lines to it without closing it at the end of each iteration.

Run the console app and you should see “File write done” almost instantly. The most expensive method, i.e. WriteNumbersToFile has to get hold of a new FileLogger instance only in the first iteration and will get the same instance over and over again in subsequent loops.

Inspect the contents of the file. You’ll see that the iteration was indeed performed in a parallel way as the numbers do not follow any specific order, i.e. the outcome is not deterministic:

Ready for next number…
Ready for next number…
Logged number: 50
Ready for next number…
Logged number: 51
Logged number: 25
Ready for next number…
Ready for next number…
Logged number: 52
Logged number: 26
Ready for next number…
Logged number: 27
Ready for next number…
Ready for next number…
Logged number: 53
Ready for next number…
Logged number: 28
Logged number: 54
Ready for next number…
Logged number: 55
Ready for next number…

etc…

So, we have successfully implemented the singleton pattern in a way that eliminates its weaknesses: this solution is threadsafe, testable and loosely coupled.

UPDATE:

Please read the tip by Learner in the comments section regarding the safety of using static initialisation:

“Cases do exist, however, in which you cannot rely on the common language runtime to ensure thread safety, as in the Static Initialization example.’ as mentioned under “Multithreaded Singleton” section of the following link on MSDN. Instead of using static initialization, the msdn example uses volatile and Double-Check Locking and I have seen people mostly using the same.”

View the list of posts on Architecture and Patterns here.

Design patterns and practices in .NET: the Null Object pattern

Introduction

Null references are a fact of life for a programmer. Some would actually call it a curse. We have to start thinking about null references even in the case of the simplest Console application in .NET.:

static void Main(string[] args)

If there are no arguments passed in to the Main method and you access the args array with args[0] then you’ll get a NullReferenceException because the array has not been initialised. You have to check for args == null already at this stage.

This problem is so pervasive that if your class or method has some dependency then the first thing you need to check is if somebody has tried to pass in a null in a guard clause:

if (dependency == null) throw new ArgumentNullException("Dependency name");

Also, if you call a method that returns an object and you intend to use that object in some way then you may need to include the following check:

if (object == null) return;

…or throw an exception, it doesn’t matter. The point is that your code may be littered with those checks disrupting the flow. It would be a lot more efficient to be able to assume that the return value has been instantiated so that it is a ‘valid’ object that we can use without checking for null values first.

This is exactly the goal of the Null Object pattern: to be able to provide an ’empty’ object instead of ‘null’ so that we don’t need to check for null values all the time. The Null Object will be sort of a zero-implementation of the returned object type where the object does not perform anything meaningful.

Also, there may be times where you just don’t want to make use of a dependency. You cannot pass in null as that would throw an exception – instead you can pass in a valid object that does not perform anything useful. All method calls on the Null Object will be valid, meaning you don’t need to worry about null references. This may occur often in testing scenarios where the test may not care about the behaviour of the dependency as it wants to test the true logic of the system under test instead.

Of course it’s not possible to get rid null checks 100%. There will still be places where you need to perform them.

This pattern is also known by other names: Stub, Active Nothing, Active Null.

Demo

Open Visual Studio and create a new Console application. We’ll simulate that a method expects a caching strategy to cache some object. The example is similar to and builds on the example available here under the discussion on the Adapter Pattern. Insert the following interface:

public interface ICacheStorage
	{
		void Remove(string key);
		void Store(string key, object data);
		T Retrieve<T>(string key);
	}

Insert the following concrete type that implements the HttpContext.Current.Cache type of solution:

public class HttpContextCacheStorage : ICacheStorage
	{

		public void Remove(string key)
		{
			HttpContext.Current.Cache.Remove(key);
		}

		public void Store(string key, object data)
		{
			HttpContext.Current.Cache.Insert(key, data);
		}

		public T Retrieve<T>(string key)
		{
			T itemsStored = (T)HttpContext.Current.Cache.Get(key);
			if (itemsStored == null)
			{
				itemsStored = default(T);
			}
			return itemsStored;
		}
	}

You’ll need to add a reference to System.Web. It’s of course not too wise to rely on the HttpContext in a Console application but that’s beside the point right now.

Add the following private method to Program.cs:

private static void PerformWork(ICacheStorage cacheStorage)
{
	string key = "key";
	object o = cacheStorage.Retrieve<object>(key);
	if (o == null)
	{
		//simulate database lookup
		o = new object();
		cacheStorage.Store(key, o);
	}
	//perform some work on object o...
}

We first check whether object ‘o’ is available in the cache provided by the injected ICacheStorage object. If not then we fetch it from some source, like a DB and then cache it.

What if the caller doesn’t want to cache the object? They might intentionally force a database lookup. If they pass in a null then they’ll get a NullReferenceException. Also, if we want to test this method using TDD then we may not be interested in caching. The test may probably want to test the true logic of the code i.e. the ‘perform some work on object o’ bit, where the caching strategy is irrelevant.

The solution is a caching strategy that doesn’t do any work:

public class NullObjectCache : ICacheStorage
	{
		public void Remove(string key)
		{
			
		}

		public void Store(string key, object data)
		{
			
		}

		public T Retrieve<T>(string key)
		{
			return default(T);
		}
	}

If you pass this implementation to PerformWork then the object will never be cached and the Retrieve method will always return null. This forces PerformWork to look up the object in the storage. Also, you can pass this implementation from a unit test so that the caching dependency is effectively ignored.

Another example

Check out my post on the factory patterns. You will find an example of the Null Object Pattern there in the form of the UnknownMachine class. Instead of CreateInstance of the MachineFactory class returning null in case a concrete type was not found it returns this empty object which doesn’t perform anything.

Consequences

Using this pattern wisely will result in fewer checks for null values: your code will be cleaner and more concise. Also, the need for code branching may decrease.

The caller must obviously know that a Null Object is returned instead of a null, otherwise they may still check for nulls. You can help them by commenting your methods and classes properly. Also, there are certainly cases where an empty NullObject, such as UnknownMachine mentioned above may be confusing for the caller. They will call the TurnOn() method but will not see anything happening. You can extend the NullObject implementation with messages indicating this status, e.g. “Cannot turn on an empty machine.” or something similar.

Null objects are quite often implemented as singletons – the subject of the next post: as all NullObjects implementations of an abstraction are identical, i.e. have the same properties and states they can be shared across the application. This may become cumbersome in large applications where team members may not agree on what a NullObject representation should look like. Should it be empty? Should it have some minimal implementation? Then it’s wiser to allow for multiple representations of the Null Object.

View the list of posts on Architecture and Patterns here.

Design patterns and practices in .NET: the Adapter Pattern

Introduction

The adapter pattern is definitely one of the most utilised designed patterns in software development. It can be used in the following situation:

Say you have a class – Class A – with a dependency on some interface type. On the other hand you have another class – Class B – that would be ideal to inject into Class A as the dependency, but Class B does not implement the necessary interface.

Another situation is when you want to factor out some tightly coupled dependency. A common scenario would be a direct usage of some .NET class, say HttpRuntime in a method that you want to test. You must have a valid HttpRuntime while running the test otherwise the test may fail and that is of course not acceptable. The solution is to let the method be dependent on some abstraction that is injected to it – the question is how to extract HttpRuntime and make it implement some interface instead? After all, it’s unlikely that you’ll have write access to the HttpRuntime class, right?

The solution is to write an adapter that sits between Class A and Class B that wraps Class B’s functionality. An example from the real world: if you travel from Britain to Sweden and try to plug in your PC in your hotel room you’ll fail as the electric sockets in Sweden are different from those in the UK. Class A is your PC’s power plug and Class B is the socket in the wall. The two objects clearly don’t fit but there’s a solution: you can insert a specially made adapter into the socket which makes the “conversion” between the plug and the socket enabling you to pair them up. In summary: the adapter pattern allows classes to work together that couldn’t otherwise due to incompatible interfaces. The adapter will take the form of an interface which has the additional benefit of extensibility: you can write many implementations of this adapter interface making sure your method is not tightly coupled to one single concrete implementation.

Demo

Open Visual Studio and create a new blank solution. Add a new class library called Domain and delete Class1.cs. Add a new class to this project called Customer. We’ll leave it void of any properties, that is not the point here. We want to expose the repository operations by an interface, so insert an interface called ICustomerRepository to the Domain layer:

public interface ICustomerRepository
	{
		IList<Customer> GetCustomers();
	}

Add another class library called Repository and a class called CustomerRepository which implements ICustomerRepository:

public class CustomerRepository : ICustomerRepository
	{
		public IList<Customer> GetCustomers()
		{
			//simulate database operation
			return new List<Customer>();
		}
	}

Add a new class library project called Service and a class called CustomerService to it:

public class CustomerService
	{
		private readonly ICustomerRepository _customerRepository;

		public CustomerService(ICustomerRepository customerRepository)
		{
			_customerRepository = customerRepository;
		}

		public IList<Customer> GetAllCustomers()
		{
			IList<Customer> customers;
			string storageKey = "GetAllCustomers";
			customers = (List<Customer>)HttpContext.Current.Cache.Get(storageKey);
			if (customers == null)
			{
				customers = _customerRepository.GetCustomers();
				HttpContext.Current.Cache.Insert(storageKey, customers);
			}

			return customers;
		}
	}

This bit of code should be straightforward: we want to return a list of customers using the abstract dependency ICustomerRepository. We check if the list is available in the HttpContext cache. If that’s the case then convert the cached value and return the customers. Otherwise fetch the list from the repository and put the value to the cache.

So what’s wrong with the GetAllCustomers method?

Testability

The method is difficult to test because of the dependency on the HttpContext class. If you want to get any reliable result from the test that tests the behaviour of this method you’ll need to somehow provide a valid HttpContext object. Otherwise if the test fails, then why did it fail? Was it a genuine failure, meaning that the customer list was not retrieved? Or was it because there was no HttpContext available? It’s the wrong approach making the test outcome dependent on such a volatile object.

Flexibility

With this implementation we’re stuck with the HttpContext as our caching solution. What if we want to change over to a different one, such as Memcached or System.Runtime? In that case we’d need to go in and manually replace the HttpContext solution to a new one. Even worse, let’s say all your service classes use HttpContext for caching and you want to make the transition to another caching solution for all of them. You probably see how tedious, time consuming and error-prone this could be.

On a different note: the method also violates the Single Responsibility Principle as it performs caching in its body. Strictly speaking it should not be doing this as it then introduces a hidden side effect. The solution to that problem is provided by the Decorator pattern, which we’ll look at in the next blog post.

Solution

It’s clear that we have to factor out the HttpContext.Current.Cache object and let the consumer of CustomerService inject it instead – a simple design principle known as Dependency Injection. As usual, the most optimal option is to write an abstraction that encapsulates the functions of a cache solution. Insert the following interface to the Service layer:

public interface ICacheStorage
	{
		void Remove(string key);
		void Store(string key, object data);
		T Retrieve<T>(string key);
	}

I believe this is quite straightforward. Next we want to update CustomerService to depend on this interface:

public class CustomerService
	{
		private readonly ICustomerRepository _customerRepository;
		private readonly ICacheStorage _cacheStorage;

		public CustomerService(ICustomerRepository customerRepository, ICacheStorage cacheStorage)
		{
			_customerRepository = customerRepository;
			_cacheStorage = cacheStorage;
		}

		public IList<Customer> GetAllCustomers()
		{
			IList<Customer> customers;
			string storageKey = "GetAllCustomers";
			customers = _cacheStorage.Retrieve<List<Customer>>(storageKey);
			if (customers == null)
			{
				customers = _customerRepository.GetCustomers();
				_cacheStorage.Store(storageKey, customers);
			}

			return customers;
		}
	}

We’ve got rid of the HttpContext object, so the next task is to inject it somehow using the ICacheStorage interface. This is the essence of the Adapter pattern: write an adapter class that will resolve the incompatibility of our home-made ICacheStorage interface and HttpContext.Current.Cache. The solution is really simple. Add a new class to the Service layer called HttpContextCacheStorage:

public class HttpContextCacheStorage : ICacheStorage
	{

		public void Remove(string key)
		{
			HttpContext.Current.Cache.Remove(key);
		}

		public void Store(string key, object data)
		{
			HttpContext.Current.Cache.Insert(key, data);
		}

		public T Retrieve<T>(string key)
		{
			T itemsStored = (T)HttpContext.Current.Cache.Get(key);
			if (itemsStored == null)
			{
				itemsStored = default(T);
			}
			return itemsStored;
		}
	}

This is the adapter class that encapsulates the HttpContext caching object. You can now inject this concrete class into CustomerService. In the future if you want to make use of a different caching solution then all you need to do is to write another adapter for that: MemCached, Velocity, System.Runtime.Cache, you name it.

View the list of posts on Architecture and Patterns here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.