Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » C# Language » Object Instantiation in C#. Part II Factory Methods

Object Instantiation in C#. Part II Factory Methods

There are many ways to approach object instantiation. In this article we’ll cover a few of the patterns used to instantiate objects.

Author Rank :
Page Views : 19710
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

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

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

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

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

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

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);
    }
}

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

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.