Blue Theme Orange Theme Green Theme Red Theme
 
Ads by Lake Quincy Media
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Ads by Lake Quincy Media
 Resources  
Close
 Our Network  
Close
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:
Total page views :  14116
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.