Object Instantiation in C#: Part II - Factory Methods

Part II. Controlling "New-Uping"
In Part I of this series, we talked about basic instantiation and different ways constructors can work.  Now we'll look at different instantiation patterns used to control how objects are instantiated.

A Factory Method for Loose Coupling

There are a couple situations where we would want a factory method to instantiate objects.
The first situation is where we have a class that is derived from a base class or implements an interface.  A good general coding practice is to keep coding loosely coupled so generally we want to program to base classes or interfaces whenever possible.  If we create a factory method, we can control what gets returned from the factory.
  1. public class BigNumber:Number  
  2. {  
  3. }
So, in the above class, we may want to provide a reference to the "Number" base class so that all code will implement the base class properties and methods and thus deal with the newly instantiated object in terms of a "Number" class and not the more specific "BigNumber" class.  This way we our code is more loosely coupled because the dependency of the implementation is not tied to a specific implementation, but it is now dependent on a more general base class (which is what we mean by saying loose-coupling).  To expose our objects in this more general and more loosely coupled way we first  make the constructor private, ensuring that all instantiation code must be declared within the class definition, and we can create a static factory method which will be responsible for instantiating an instance of the class and exposing it as the more general base class.  As a general principle we only want to expose class functionality that is needed to do the work we want done.
In the following code, notice that the constructor is private, and to instantiate the object we now must use the New() method which is returning a reference to a instance of the "Number" base class. 
As a side note, I like calling this method "New()", because when other developers are reading my code, they can easily make sense of what is going on because they are used to associating the work "New" with instantiation.
  1. public class Two : Number  
  2. {  
  3.     private Two()  
  4.     { }  
  6.     public static Number New()  
  7.     {  
  8.         return new Two();  
  9.     }  
  10. }
In this scenario, when we want to "new-up" our class, we call it through the static method as follows:
  1. Number objTwo = Two.New(); 
The following code would not compile because the New() factory method now returns a "Number" object and not a "Two" object:
  1. Two objTwo = Two.New();

A Factory Method for Complex Object Initialization

Sometimes we have classes that take a lot of processing to initialize.  There may be dependencies to set, configuration settings to pull in, database calls that need to be made, and so on.  To keep our code clean and maintainable we should always attempt to have a method do one and only one thing.  The purpose of a constructor is to set member variables.  When we have additional work that needs to be done, it is best to keep it out of the constructor method and in a separate method responsible solely for doing initialization work.
The following constructor is poorly designed because it has multiple responsibilities.  It is responsible for both retrieving a value from the config file, and also setting the member variable.  This code will be difficult to maintain because the method is not concise and its primary purpose is not clear.
  1. public class ComplexThing  
  2. {  
  3.     public ComplexThing()  
  4.     {  
  5.         string value = ConfigurationManager.AppSettings["TheNumber"];  
  7.         if (string.IsNullOrEmpty(value))  
  8.             throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  10.         m_i = Convert.ToInt32(value);  
  11.     }  
  13.     private int m_i;  

As an alternative, we would want to factor out all code that is not setting member variables into another method.  This is a perfect case for a factory method.  Notice in the following code has much clearer the responsibilities for each method.  This makes for much more maintainable code (which you will see in a bit), especially in a project with multiple developers.  Anyone could see that the constructor is primarily responsible for setting member variables. 
  1. public class ComplexThing  
  2. {  
  3.     private ComplexThing(int i)  
  4.     {  
  5.         m_i = i;  
  6.     }  
  8.     public static ComplexThing New()  
  9.     {  
  10.         string value = ConfigurationManager.AppSettings["TheNumber"];  
  12.         if (string.IsNullOrEmpty(value))  
  13.             throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  15.         return new ComplexThing(Convert.ToInt32(value));  
  16.     }  
  18.     private int m_i;  
  19. }
One more adjustment and the code will be much more maintainable and human readable.  The problem with the above code is that the New() method is responsible for configuration retrieval, instantiation, and then managing the process. 
The following code has even clearer seperation of responsibilities in each method and would be able to survive long-term maintenance much better than the first design we had and moderately better than the second design.  There is now no question as to what the primary responsibility of each method is.
  1. public class ComplexThing  
  2. {  
  3.     private ComplexThing(int i)  
  4.     {  
  5.         m_i = i;  
  6.     }  
  8.     public static ComplexThing New()  
  9.     {  
  10.         int value = GetConfigurationValue();  
  11.         return new ComplexThing(value);  
  12.     }  
  14.     private static int GetConfigurationValue()  
  15.     {  
  16.         string value = ConfigurationManager.AppSettings["TheNumber"];  
  18.         if (string.IsNullOrEmpty(value))  
  19.             throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  21.         return Convert.ToInt32(value);  
  22.     }  
  24.     private int m_i;  

A Factory Class

Another pattern is to just move the Factory method into its own class.  This design would be considered to have a higher level of cohesion because each class has a more specific purpose.  A high level of cohesion in class design directly correlates with having a more robust, reliable, understandable, reusable and testable code base (in other words, it's a really good idea).
Just as a side note: This refactoring is relatively simple using the above code, because we already have seperation of responsibility in each method which is a prime example of how much easier it is to work with methods having distinct responsibilities versus methods that have multiple responsibilities.  I hope it is clear how much harder it would have been to move our first implementation of the ComplexThing class to the example below.  We should always be aware of how cohesive our code is because it makes life much easier when requirements start changing, and if we have an end product that has value and any kind of life span, we can almost always count on changes.
  1. public class ComplexThing  
  2. {  
  3.     internal ComplexThing(int i)  
  4.     {  
  5.         m_i = i;  
  6.     }  
  8.     private int m_i;  
  9. }  
  11. public class ComplexThingFactory  
  12. {  
  14.     public static ComplexThing Create()  
  15.     {  
  16.         int value = GetConfigurationValue();  
  17.         return new ComplexThing(value);  
  18.     }  
  20.     private static int GetConfigurationValue()  
  21.     {  
  22.         string value = ConfigurationManager.AppSettings["TheNumber"];  
  24.         if (string.IsNullOrEmpty(value))  
  25.             throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  27.         return Convert.ToInt32(value);  
  28.     }  
  29. }
Notice that the accessor for the ComplexThing class has been set to "internal".  This ensures that nothing outside this assembly will be able to instantiate the class. Because the ComplexThingFactory is in the same assembly, it can instantiate the ComplexThing and we are still controlling the instantiation to a degree.
In the next article, we'll look at building a couple kinds of abstract factories.
Until next time,
Happy coding

Similar Articles