Object Instantiation in C#: Part II - Factory Methods

Before reading this article, kindly go through the previous parts.

A Factory Method for Loose Coupling

There are a couple of 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.

public class BigNumber:Number  
{  
}

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, 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 that 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 the 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 returns a reference to an 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 word "New" with instantiation.

public class Two : Number  
{ 
    private Two()  
    { }  
  
    public static Number New()  
    {  
        return new Two();  
    }  
}

In this scenario, when we want to "new-up" our class, we call it through the static method as follows.

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.

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 setting the member variable.  This code will be difficult to maintain because the method is not concise, and its primary purpose is not clear.

public class ComplexThing  
{  
    public ComplexThing()  
    {  
        string value = ConfigurationManager.AppSettings["TheNumber"];  
  
        if (string.IsNullOrEmpty(value))  
            throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  
        m_i = Convert.ToInt32(value);  
    }  
  
    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 that the following code has much clearer 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. 

public class ComplexThing  
{  
    private ComplexThing(int i)  
    {  
        m_i = i;  
    }  
  
    public static ComplexThing New()  
    {  
        string value = ConfigurationManager.AppSettings["TheNumber"];  
  
        if (string.IsNullOrEmpty(value))  
            throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  
        return new ComplexThing(Convert.ToInt32(value));  
    }  
  
    private int m_i;  
}

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 an even clearer separation 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.

public class ComplexThing  
{  
    private ComplexThing(int i)  
    {  
        m_i = i;  
    }  
  
    public static ComplexThing New()  
    {  
        int value = GetConfigurationValue();  
        return new ComplexThing(value);  
    }  
  
    private static int GetConfigurationValue()  
    {  
        string value = ConfigurationManager.AppSettings["TheNumber"];  
  
        if (string.IsNullOrEmpty(value))  
            throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  
        return Convert.ToInt32(value);  
    }  
  
    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 a separation 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.

public class ComplexThing  
{  
    internal ComplexThing(int i)  
    {  
        m_i = i;  
    }  
  
    private int m_i;  
}  
  
public class ComplexThingFactory  
{  
  
    public static ComplexThing Create()  
    {  
        int value = GetConfigurationValue();  
        return new ComplexThing(value);  
    }  
  
    private static int GetConfigurationValue()  
    {  
        string value = ConfigurationManager.AppSettings["TheNumber"];  
  
        if (string.IsNullOrEmpty(value))  
            throw new ConfigurationErrorsException("configuration setting TheNumber is not available");  
  
        return Convert.ToInt32(value);  
    }  
}

Note. 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.

To better understand the article, please go through the next parts.


Similar Articles