Abstract Factory Design Pattern

In the earlier posts I covered Factory Design Pattern. This post is about Abstract Factory Design Pattern. At times it is confusing to understand the need for two patterns which are related to the concept of factories. In simple terms Abstract Factory is like a factory of factories. Lets examine the details of this pattern and try to compare it with others that I have already covered in the previous posts.

Problem statement

Lets assume that we have some data with us in the form of a collection. It can be anything like list of people and their details, bank transaction details, employee salary details etc. I am not really worried about the format and exact representation of the data. What I know for sure is there is a collection of data in my possession. I need to export this data as report into different formats. Currently the supported formats are HTML and plain text. The report should have a header row displaying column name. Then should be actual content in the report details section and finally a footer to display summary information.

Implementation

Note that for simplicity I am not going to actually build any report. I’ll build the skeleton which can be extended to build a proper report if you really wish to. Instead of discussing the theory lets look at some code to get started.

    public class ReportWriter

    {

        public void GenerateReport(ReportOptions reportOptions)

        {

            if (reportOptions.ReportType == ReportType.HTML)

            {

                HTMLReportHeader htmlHeader = new HTMLReportHeader();

                htmlHeader.WriteHeaderDetails();

 

                HTMLReportContent htmlContent = new HTMLReportContent();

                htmlContent.WriteContents();

 

                HTMLReportFooter htmlFooter = new HTMLReportFooter();

                htmlFooter.WriteFooterDetails();

            }

            else if (reportOptions.ReportType == ReportType.Text)

            {

                TextReportHeader textReportHeader = new TextReportHeader();

                textReportHeader.WriteHeaderDetails();

 

                TextReportContent textReportContent = new TextReportContent();

                textReportContent.WriteContents();

 

                TextReportFooter textReportFooter = new TextReportFooter();

                textReportFooter.WriteFooterDetails();

            }

        }

    }

This is a skeleton which consists of a set of classes for specific purpose like the HTMReportLHeader, HTMLReportContent and HTMLReportFooter for handling HTML report. Similarly there is text equivalent of this in the form of TextReportHeader, TextReportContent and TextReportFooter. In real life these methods would be much more complex and would require various inputs like the actual report data, the header details and footer details. Once again I have omitted them for demo purposes.

Refactoring towards Abstract Factory

The above solution works for simple cases. In most cases what starts as a simplest requirement ends up complicating things in future as business users change their requirements. It is always better to build software which is easier to change in future with minimal efforts. The problems with the above solution is similar to the ones we have seen in earlier posts. The biggest of them all is the extensibility.

Imagine the users of the system also want a report in Excel or PDF or XML, or for that matter any other format which they might be comfortable with. We can keep adding the else if cases or refactor this logical tree into a switch case statement. One thing to remember is every time we add a type of report we’ll end up adding at least 3 classes for header, report details and the  footer. And in most cases only one set of these related classes would be used at a point of time.

Instead of building a big chunk of if else or switch case construct, we can simply things by abstracting these classes into a family of closely related classes. If we look closely all we need is an interface which can be called by the report write and an abstraction for each of the specific section of the report which are header, contents or details and the footer. Lets start by building the interface which will help us with these abstractions.

    public interface IReportGenerator

    {

        IReportHeader GetReportHeader();

 

        IReportContent GetReportContent();

 

        IReportFooter GetReportFooter();

    }

A simple interface with 3 methods. The magic lies in this abstraction. Note that the interface does not expose the concrete types but in turn it exposes the abstractions of the related or family of objects. Lets look at an implementation of this interface.

    public class HTMLReportGenerator : IReportGenerator

    {

        public IReportHeader GetReportHeader()

        {

            return new HTMLReportHeader();

        }

 

        public IReportContent GetReportContent()

        {

            return new HTMLReportContent();

        }

 

        public IReportFooter GetReportFooter()

        {

            return new HTMLReportFooter();

        }

    }

This is the implementation of HTMLReportGenerator. In this we return the concrete instance of the other interfaces like HTMLReportHeader, HTMLReportContent and HTMLReportFooter. I’ll not show the implementation of each and every class here. Lets see what changes are required in the client code

    public class ReportWriter

    {

        public void GenerateReport(ReportOptions reportOptions)

        {

            IReportGenerator reportGenerator = ReportGeneratorFactory.GetReportGenerator(reportOptions.ReportType);

 

            reportGenerator.GetReportHeader().WriteHeaderDetails();

 

            reportGenerator.GetReportContent().WriteContents();

 

            reportGenerator.GetReportFooter().WriteFooterDetails();

        }

    }

I refactored the ReportWriter class to work with the IReportGenerator abstraction. We obtain the concrete instance of this abstraction using the ReportGeneratorFactory class which is responsible for creating the concrete instance based on the input parameter of ReportType.

    public class ReportGeneratorFactory

    {

        public static IReportGenerator GetReportGenerator(ReportType reportType)

        {

            switch (reportType)

            {

                case ReportType.HTML:

                    return new HTMLReportGenerator();

                case ReportType.Text:

                    return new TextReportGenerator();

            }

        }

    }

We can always counter these refactoring's as not a big deal. If you think so, just try implementing the report writer for only the formats I have accounted here which include HTML report, text report, XML report and Excel report.

By abstracting the interface we have made our solution quite extensible and simple to maintain. Imagine the business users come up with a new requirement to generate a report in XPS format. All we need is to implement a case statement which returns a XPSReportGenerator. Off course the dependent interfaces will need to be developed. But the client code is totally unaware of which exact type is being used at runtime. As long as the IReportGenerator interface is implemented by the deriving classes client will continue to generate reports of all types.

This allows us the flexibility to control features on demand basis. Imagine you want to expose selective functionality to specific users. Lets say the software being developed has a free or lite version and also a paid version. We can provide different sets of reports based on their needs. In lite version only HTML and Text reports can be supported and in the full blown version all types of reports can be supported.

Example of Abstract Factory used within .Net Framework

One of the best example of Abstract factory used within .Net framework is the ADO.NET. Look at the interfaces provided over the database specific types like IDbConnection, IDataReader, IDbCommand etc. Specific providers implement these interfaces like SqlConnection, SQLCommand, SqlDataReader in case of SQL server. Similarly Oracle provides OracleConnection, OracleDataReader and OracleConnection. Same is the case with other database providers like OLEDb, Sybase etc. All these vendors implement the generic interfaces. This is what allows .Net framework to provide an abstract factory in the form of DbProviderFactory which can build provider specific instances of the respective classes.

Conclusion

I might not have written the complete implementation of all the concrete classes, but I hope the skeleton was good enough to put my thoughts across. Abstract factory design pattern is very helpful when we want a set of classes to work together. These classes are always related to one another and very rarely be used outside the context of their boundary. For example the HTML report related classes will be used in the HTML report generator. I cannot imagine an Excel report generator using a HTMLFooter class to write an excel footer row. When we have such scenario of closely related classes working together in unison its always a better idea to group them using an Abstract Factory.

In many ways the code might look similar to the one we used during the demonstration of Strategy Design Pattern. We can say that report writer class is just another strategy like a HTMLStrategy, TextStrategy, XMLStrategy, PDFStrategy etc etc. Its not like we cannot implement the same pieces as a strategy. One very important thing to remember while implementing and using design patterns is their intent and the applicability. For the same problem statement we can possibly apply more than one design pattern. We need to pick and choose the best one. This is when the intent helps us a lot.

The intent of a Strategy pattern is to swap an algorithm. Where as Abstract Factory design pattern is used to abstract the creation of families of objects which work closely with one another. Strategy is used when there are multiple ways of achieving the same results but using different mechanisms which are essentially abstracted in the form of algorithms. In case of abstract factory the intent is to hide the concrete implementations behind a common interface for a set or related classes. In this case I have used an interface but the same can be implemented using an abstract base class. Another difference between the two patterns is that Strategy is a behavioural pattern while Abstract Factory is a creational pattern.

As always I have uploaded the code used during this demo to Dropbox.

Until next time Happy Programming.

Further reading

 

spacer

Continuous Testing using NCrunch

Long ago I had a discussion with Jesse Fewell who was coaching the teams in my previous organization on Agile adoption. During one of the casual talks he told me that if you are a developer you should do certain things. One of those very important thing is to automate as much as possible any repetitive task. I am always on the lookout for tools and utilities which can help me in getting the job easier and faster. Recently I came across a continuous testing tool called NCrunch. This post is about my experience in using NCrunch.

Get started with NCrunch

To get started, we need to install the Visual Studio add in from www.nchrunch.net. Go to the downloads section and install the MSI package. After the successful installation we get an additional menu in the VS IDE as shown below

image

By default NCrunch starts in disabled mode. At the time of taking this screenshot, it is already enabled and we just need to select the first option from the menubar to toggle the NCrunch. If we are enabling NCrunch for a solution for the first time, we’ll have to configure the options for the runner. We can also edit / update the configuration settings using the Run Configuration Wizard option. Here are some things which I found useful.

CPU selection

CPU Configuration allows us to assign the number of CPU cores we can use during the test execution. The description is self explanatory in the configuration screen. I used the default settings, if you wish you can assign more cores to the Visual Studio or NCrunch.

 

 

 

 

Processing Threads

Max Processing Threads allows us to configure the number of threads NCrunch should use for test execution. Once again I had used the default option. If you wish to run the tests in parallel, you can increase the number of threads.

 

 

 

 

Parallel Test Execution

Parallel Test Execution option is used to set up NCrunch to run tests in sequential mode or parallel mode.

 

 

 

 

 

 

 

Engine Execution Mode

Engine Execution Mode is used to decide when the tests should be run depending on the changes to the source code. Once again the options are self explanatory.

 

 

 

 

 

 

We are ready to use NCrunch continuous test running service with these settings. Note: I have used a project from one of my previous posts on Strategy Design Pattern for demonstration purpose here.

Lets start by looking at the Calculator class without applying the strategy pattern from the earlier demo.

NcrunchCoverage

We see on the left hand side that most lines have green dots. That is one of the feature of NCrunch which I like. It shows the Code Coverage for a file. The colour coding is similar to that of Visual Studio code coverage which shows different colours for lines fully covered, partially covered and uncovered using different colours. No need to enable code coverage, run tests to see which lines are covered and which are not. NCrunch makes it dead simple. In this case all the lines are covered.

Lets comment one of the test related to this file and see the impact on the inline code coverage of NCrunch. I added the Ignore attribute to one of the test method and immediately the colour changes in the source file.

PartialCodeCoverage

That is a big plus for me. I have been using various unit testing frameworks for close to 8 years and I don’t remember any of the test runners providing such features built into the product. Some may argue that Visual Studio has Test Impact Analysis feature. I have used it very limited number of times. My experience is that it is very slow and the overall performance is very bad. Instead of speeding things up it slowed me down when I used it.

We can hover over the dots and it provides additional context sensitive information.

CoverageTooltip

As can be seen from the above screenshot, if I hover over a green dot it tells me how many passing / failing tests are covering this particular line of code. Once again I have not come across such feature in any other tool so far. What I like about this feature is the drill down facility. We can left click and double click on the test which covers the code and navigate to the test code.

TestDrillDown

We can also right click and choose from other options.

RightClickOptions

Along with the context based options we also get instant feedback after making changes to the code. This code can be either in the class under test or the test class. In both cases we get automatic updates in the IDE. Lets change one of the constant values for the interest rates and see how NCrunch adapts to it. I’ll change the value of 2nd constant from 10 to 20.

BreakingCode

Immediately we get red dots on almost all lines of code because there is associated unit test or set of tests which are failing related to these lines of code. Lets look at the way the Test class is represented when NCrunch is enabled.

TestClass

Here also the failing tests are represented by red dots. We can revert the change to the constant value and things would turn green again. Or else we can fix the related unit tests to take into account the refactoring to the code.

Conclusion

All this happens while we finish typing the changes in the IDE. There is no need to run the tests or even to compile the code. NCrunch takes care of that in the background and we get instant feedback. I see this as a definite time saver. On large projects you can imagine how much time we spent on compiling and running tests. A lot of that can be saved using parallel test execution using NCrunch. Imagine  the amount of time we spent in looking for tests which covers a piece of code. You can argue that Visual Studio provides a method using “Find All References” to get a list of all references to a method. But there is no built in way of navigating directly to the test code like the one provided by NCrunch.

Focussing on running only the impacted tests is a big advantage for NCrunch. It beats the Test Impact Analysis feature of Visual Studio comfortably in terms of performance and speed. And by the way if I have read correctly, then in VS 2011 Test Impact Analysis is already deprecated. I have not seen such quick feedback in other tolls that I have used for unit testing. 

There are other features of NCrunch which I like. But I’ll stop at this point and probably cover them in future. For time being if you are a fan of TDD I would suggest you to explore NCrunch. Its a free tool and very easy to setup.

Until next time Happy Programming Smile

 

Further reading

 

spacer

Singleton Design Pattern

One of the simplest and easiest to understand among design patterns is the Singleton Design Pattern. It is a creational pattern which centralizes the creation of an instance of a class. This also helps to ensures that the class has only one instance across application. Singleton provides a global access to an instance of a class.

Problem statement

Imagine we want to ensure that only one instance of a class is created within an application. This class can be a application host class like App in a WPF / Silverlight application or some of the operating system services like the logon service or the service which listens to the mouse or keyboard events. We need to ensure that at any point of time there is only one instance of this services.

Classic Singleton

In order to ensure that there is only one instance of a class across an application boundary, we can restrict the mechanism through which new instances of a class are created. In C#, since we use constructors to create new instances, we can restrict the constructor itself. In general the constructors are mostly publicly accessible. But in case of Singleton implementation we make the constructor as private. This means that we cannot create a new instance of a class using the constructor from any other class. By making the constructor private, we force the class to take the responsibility of creating its own instance. Here is a classic implementation of the Singleton pattern as described in the Gang of Four book.

    public class SimpleSingleton

    {

        private static SimpleSingleton _instance;

 

        private SimpleSingleton()

        {

        }

 

        public static SimpleSingleton Instance

        {

            get

            {

                if (_instance == null)

                {

                    _instance = new SimpleSingleton();

                }

 

                return _instance;

            }

        }

    }

In order to create an instance we create a static property or a method. In this case I have used a property. Note that this is a ready only property. In order to control the number of instances, we have declared a private static member variable. As a convention this private member as well as the public property are both named as _instance and Instance respectively. We can name it anything we would like. The getter check if the _instance is null and creates a new one if that is the case. Otherwise it simply returns the already created instance. This way we have ensured that there is only one instance of this class and also it can be created only using the same class.

This solution works fine in a single threaded model. In todays world where most of the CPU’s are multi core and most applications support multi threading in native ways, this code is bound to create problems. If multiple threads are accessing the Singleton and trying to create an instance at the same time this code is bound to fail in the step where we are trying to check if the _instance is null. One thread might find that the _instance is null and call the private constructor. Before the object is initialized, another thread might try to execute the same code and since the _instance is uninitialized another new instance might be created. This scenario clearly defeats the purpose of creating a Singleton instance.

Thread safe Singleton

To overcome this problem, we can use the synchronization mechanism and control the access to the constructor as shown below.

    public class ThreadSafeSingleton

    {

        private static ThreadSafeSingleton _instance;

        private static object _synchronizingObject = new object();

 

        private ThreadSafeSingleton()

        {

        }

 

        public static ThreadSafeSingleton Instance

        {

            get

            {

                if (_instance == null)

                {

                    lock (_synchronizingObject)

                    {

                        if (_instance == null)

                        {

                            _instance = new ThreadSafeSingleton();

                        }

                    }

                }

 

                return _instance;

            }

        }

    }

This approach makes the Singleton implementation Thread safe. We acquire a lock before creating a new instance. And to be double sure that the instance is not yet initialized, we check for the null value. This double checking prevents two threads from simultaneously accessing the private constructor.

Optimized Singleton

All this seems bit too much just to control instancing of an object. Dotnet framework provides an optimized way of implementing a singleton using readonly variables.

    public sealed class OptimizedSingleton

    {

        private static readonly OptimizedSingleton _instance = new OptimizedSingleton();

 

        private OptimizedSingleton()

        {

        }

 

        public static OptimizedSingleton Instance

        {

            get

            {

                return _instance;

            }

        }

    }

By marking the private variable as readonly, we can take care of the thread safety. The readonly variables can only be assigned during static initialization like I have done here or through a constructor. This approach is the simplest among all.

Conclusion

We saw 3 ways of implementing singleton pattern in this post. Since all the 3 approaches are already available here as inline code, this time for a change I have not uploaded the complete working solution. There is only one class involved in singleton apart from the client who uses the singleton instance. In most modern day applications we are using some for of Inversion of Control (IoC) container. These containers have built in support for converting a normal class into a singleton without writing any additional lines of code. You can use this approach demonstrated here to implement singleton pattern if you are one of those persons who do not use any IoC container for object lifecycle management. I would recommend using any of the commonly available IoC container like Spring.Net, StructureMap, Castle Windsor, NInject etc to manage the lifetime of objects as well as to resolve the dependencies among objects. It can save a lot of boilerplate code like the one shown here.

Until next time Happy Programming Smile

 

Further reading

Here are some books I recommend related to the topics discussed in this post.

spacer