Creational Design Pattern: Factory Pattern

The Factory Pattern is a widely used design pattern used for the creation of object instances within an object orientated environment. The factory pattern allows us to hide the details of an object’s creation from the consumer, decoupling the consumer from an instance of an interface or a derivative of a base class.

The Factory Pattern can be used to replace the concept of class constructors, abstracting the creation of the object as to determine the construction logic at runtime. The most basic way to understand this is, you ask for an instance and the Factory Pattern Implementation provides it.

Advantages to using the Factory Pattern include;

  • Abstraction of complexity of selecting an interface implementation to use
  • Separates creation & use
  • Allows a wrapper to customise any logic required in the creation without having an effect upon the implementation itself
  • Places the creation logic in a single location
  • Allows for the management of a singleton lifecycle from within a Factory
  • Implementations are easily changed without affecting client code
  • Parameter specific instances can be easily created and stores
    • I.E – If class A requires an input parameter, say a number, which is the only change in state to the class, a series of singleton-esque instances can be created by caching a version of the class for each parameter requested.
    • If we request the class for 3 numbers, 1, 2 & 2, we would only maintain two instances of the class, one for the parameter 1, and one for the parameter 2.


Since a Factory is typically associated with the manufacturing process, I’ll use a traditional example of creating a vehicle based on the current environment.

Here, we have an application that requires a Vehicle, based on the current Environment. By Environment, I don’t mean technical environment, but a representation of a physical location, for example, a field.

We begin by defining the interface of the vehicle;

public interface IVehicle

    Terrain Terrain { get; }

public enum Terrain


Then we create the implementations of the interface;

public class Car : IVehicle


    Terrain Terrain { get { return Terrain.Land;  }}


public class Plane : IVehicle


    Terrain Terrain { get { return Terrain.Air;  }}


public class Boat: IVehicle


    Terrain Terrain { get { return Terrain.Sea;  }}


In our imaginary application, somewhere in a dank, dark and scary cellar we have a setting that tells us what the current Terrain is. This isn’t required for the Factory pattern, though it is necessary for this example to show why the factory Pattern may be used.

public static class CurrentLocation


    public static Terrain CurrentTerrain { get; set; }


Finally, we can implement the factory;

public static class VehicleFactory

public static IVehicle GetVehicle()
        if (CurrentLocation.CurrentTerrain == Terrain.Land)
            return new Car();
        else if (CurrentLocation.CurrentTerrain == Terrain.Air)
            return new Plane();
        else if (CurrentLocation.CurrentTerrain == Terrain.Sea)
            return new Boat();
            throw new Exception();

Now we have an implemented factory, the client code ca recieve a vehicle based on the current terrain setting, without having to affect any of the implementations, or have them be aware of each other. The calling client code simply cares it recieves an IVehicle, and nothing else about it matters.

IVehicle currentVehicle = VehicleFactory.GetVehicle();

Should the implementations change, or further Terrians be introduced to the application, only the factory needs to be aware, meaning the client code and implementations remain agnostic.

In all, The Factory Pattern is incredibly easy to implement, but also incredibly helpful. I imagine that at some point you will have seen one, even without realising that’s what a Factory Pattern looks like. Which can be said for most of the design patterns used in software architecture.

The client remains agnostic of the creation of the object, no matter how much the factory changes or the implementations themselves, the client code continues to function without requiring any changes.

17. December 2014 by Adam Riddick
Categories: Achitecture, Design & Practice | Leave a comment

Structural Design Pattern: Adapter

As a continuance with the Software Design Pattern that  begun with the Singleton Pattern last week, today I will discuss and demonstrate the Adapter Design Pattern.

Adapter Pattern

The Adapter Design Pattern does exactly as one would presume, it allows for incompatible interfaces to communicate through an adaption layer. The finest example of an adapter is using the electrical energy system, specifically plugs.

European Plug Socket  UK Plug

Image Courtesy of

As you can imagine, the above plug (UK Standard) will not fit the socket (European Standard Wall Socket). However, this does not mean a device using the BS 1363-1 standard plug (UK Standard, Above) won’t be able to use a European plug socket. It is in this situation that we would use an Adapter to ensure the two incompatible interfaces can interact with each other, without ever knowing they have been manipulated.

Continue Reading →

08. December 2014 by Adam Riddick
Categories: Achitecture, Design & Practice | Leave a comment

Creational Design Pattern: Singleton

For a long time now I’ve been telling myself I’ll blog a series on the various Design Patterns available to us for software architecture, and I’ll begin that today looking at the Singleton design pattern.

Whilst the examples used in this mini-series are provided in C#, they can be transposed and are applicable in every language.

Software Architecture Design Patterns are solutions for commonly occurring problems that all developers, or architects, face. The pattern itself is not a finished solution but rather a template or concept used in the creation of a solution. Generally speaking, there are multiple methods that can be used to implement design patterns, which may be dependent on language. However, the concept remains language agnostic.


I’ll begin this mini-series in discussing the Singleton design pattern.

The singleton design pattern ensures that only a single instance of an object is held at any one given moment, that is shared with all users of an application instance.

Continue Reading →

02. December 2014 by Adam Riddick
Categories: Achitecture, Design & Practice | 2 comments

C# Using Debug.Assert

Debug.Assert is a member of the System.Diagnostics library that can be used to validate a condition, pausing the running of an application is the condition is not satisfied.

Quoting from Code Complete (I highly suggest giving it a read if you haven’t already);

8 Defensive Programming

8.2 Assertions

An assertion is code that’s used during development—usually a routine or macro—that allows a program to check itself as it runs. When an assertion is true, that means everything is operating as expected. When it’s false, that means it has detected an unexpected error in the code. For example, if the system assumes that a customer-information file will never have more than 50,000 records, the program might contain an assertion that the number of records is lessthan or equal to 50,000. As long as the number of records is less than or equal to 50,000, the assertion will be silent. If it encounters more than 50,000 records, however, it will loudly “assert” that there is an error in the program.

Assertions are especially useful in large, complicated programs and in high reliability programs. They enable programmers to more quickly flush out mismatched interface assumptions, errors that creep in when code is modified, and so on.

An assertion usually takes two arguments: a boolean expression that describes the assumption that’s supposed to be true and a message to display if it isn’t.

Asserts should be used to sanity check against developer assumptions.

Debug.Assert is, as you can probably (hopefully) guess at this point, an assertion. One that runs in debug mode only. Once the application is compiled into release mode, the debug.assert is dropped from the compilation. They can be used as sanity checks in certain points of an application, and the c# implementation, Debug.Assert, will pause the running of an application and provided the current call stack and a bespoke message, provided by the developer.

Using Debug.Assert allows us to catch unexpected conditions and, as stated above, to check assumptions we have made as developers.

For example, consider the following method;

public string ReturnVal(string val)

    if (val == null) throw new ArgumentNullException("val");
    return val;

Harmless in itself, but consider the following;

string myValue = "Default Value";



    myValue = ReturnVal(myClass.Value);


catch(Exception) //Eugh, only here to prove a point


    //Do nothing


// .... Some other code to save myValue in the database

Without a constant breakpoint, we could end up saving “Default Value” in a database record, assuming that the value has never changed, when in fact myClass wasn’t loaded properly in the first place, and should have been handled better. (I know, poor case example.)

In order to force the application to pause if val is null, we can use Debug.Assert, and if the situation arises, we’ll be aware of it.

public string ReturnVal(string val)

if (val == null)
    Debug.Assert(false, "Val is null: " + val);
    throw new ArgumentNullException("val");

return val;

Using the above alteration, if val is ever null, the application will pause, in debug mode only, and return the error message. The boolean value represents the condition Debug.Assert is checking, and could also have been written as;

Debug.Assert(val != null), "Val is null: " + val); 


Debug.Assert can’t leak through into production code (Release Builds). However, should these be a need to continue using asserts in production, Trace.Assert can be used in it’s place.

This does come with an overhead.

21. November 2014 by Adam Riddick
Categories: C#, Tips | Leave a comment

Count tables in a SQL Database

Today I hit an odd error with Entity Framework 6, finding myself with a need to Count tables in a SQL Database.

The error occurred when … Well I don’t really know.

I was debugging an application we’ve been working on for a number of months now when I hit a (somewhat juvenile) mistake on one of the pages. I’d called a parameter based constructor from inside a Linq query.


So I stopped debugging and fixed the statement, to use the parameter less constructor, making a small tweak in the following code to handle the assignments myself, and I performed a Clean, followed by a Build, and then I hit debug again, to which I was given the following;

Model backing the context has changed

I was puzzled as to what had changed, so I created a migration to take a look. And what I got shocked me. The code migration created (Which I had called ‘What-The-F*ck-Has-Changed’ out of frustration’) was dropping my entire database, every relationship, index and table. So I dug a little deeper to see what EF6 wasn’t detecting through the context.

In order to do so, I found myself in need for a quick count of all the database tables, to compare against the EF6 model to find out what had went wrong. I used the following script to count tables in a SQL database backing the application;

USE DatabaseName
SELECT COUNT(*) from information_schema.tables
WHERE table_type = 'base table'

The count returned a value differing to the EF context, which was missing the relationship tables (I found after digging a little deeper). However, this was one situation where it helped to count tables in a SQL database.

But What Happened?

Your guess is as good as mine. Removing my temporary files (Now a batch script it’s needed that often) and firing off a rebuild seemed to remove the problem. In all, I just wanted to share the SQL for counting the tables within a database.


In order to discover the relationship tables where missing from the context (It wasn’t just relational tables missing, it was also 3 standard tables) I first stepped-through the application to find the set of models recognized by the context and compared that to the database tables, using Excel. To get the list of database table names to copy straight to excel, I used the following script;

USE DataAccess
SELECT * FROM information_schema.tables

10. November 2014 by Adam Riddick
Categories: SQL | Leave a comment

Find Active Directory Group Members in SQL Server

Active Directory Group Members in SQL

SQL Server is brilliant.

It’s a pleasure to work with, sometimes the queries and structures required are complex and a challenge to implement, but ultimately you can rely on the SQL engine doing it’s job, so you can focus on yours.

This isn’t always the case. Take Visual Studio for example. The environmental issues we have hit in recent development have cost us more time than any poor architectural decisions we have stumbled into. You just don’t get that when using the SQL Server engine, or perhaps I just know more about the SQL Engine than I do Visual Studio.

Recently, someone approached me whilst I was constructing some queries within SSMS, and asked me to check if they were a member of an active directory group that had permissions to a certain folder held on the shared drive. At the time I was sat thinking to myself, I’d love to be a full blown DBA, SQL Server is great, and I enjoy working with it, and so the thought crossed my mind when I was asked the question;

Can I Find Active Directory Group Members in SQL?

So, on with a little hunt I went, and I came across the xp_logininfo transact SQL statement, which will return information about Window’s User’s and Groups.

 EXEC master.dbo.xp_logininfo 'DomainName\AccountName'

Executing this command will show information regarding the user entered, including the object type, group membership and the login name the account maps to.

Experimenting a little, I discovered you can execute this same command against a Group object to view the members of the Group in question;

<EXEC xp_logininfo 'Domain\GroupName'

And with a whizz and a bang, I can view the members of the domain group.

It truly is easy to find active directory group members in SQL Server.

31. October 2014 by Adam Riddick
Categories: Databases, SQL, Tips | Leave a comment

Agility In Design

The overall design and user experience have a much greater precedence in web development than they do in traditional software engineering. In this era of “Web 2.0″, agility in design is essential to the success of any web application. As much as it pains me to stake this, as a developer, but we all know that visual effect amount to going on for 100% of initial impression.

It Human Nature, we just can’t help aesthetic judgement.

When leading projects, this poses an additional consideration in planning for the development lifecycle.

At what stage does the design kick in?

Typically, development can be driven by design. If all of the designs are produced up front, it can lead to lost time from the development team in fixing issues caused during development. However, if the designs aren’t produced until the end of the cycle, it can lead to scope creep, additional features expected by designers that have not been created by developers as they were not part of the initial scope definition.

As an alternate, design can become a part of the sprint process, if you are being agile about it. Though this can lead to a combination of the above issues, but with a much smaller feedback cycle. This is ideal as it can lead to hidden, un-scoped features being made transparent, though can still eat up a lot of development time when the functionality calls for a change in design, or vice versa.

Agility In Design is an essential part of web development, if working to a set design. But the Agility must come from all of those concerned. The development team can’t expect the design team to change everything for them, and the design team cat expect that of the development team. Everything must work well together and compromise must be given, where warranted.

There is a third approach, which is one being used on the current project I am working on. Design and Development are running simultaneously, with a development team and a separate design team. The design’s scope creep is rejected, with only agreed on features and functionality being delivered, and the development team don’t have to tread carefully around the implemented design.

This is made possible through a template design approach. The systems templates will change over time, through any number of implementations, and we are reacting t this early by ensuring we develop without a UI, so it can instead be supplanted into the finished project, in multiple forms over multiple instantiations.

To me, this is a better defined Agility In Design. The system does not care about or rely on it’s aesthetics, which can be easily adapted around the functionality.

New functionality required by new designs goes where it belongs, into a prioritised backlog of work, and scope creep ends up where it belongs, in one of the many office bins.

Whilst this approach is, to date, working brilliantly within our team, It may not necessarily be the best approach for all projects. Every project is different, as is every team, and it will always remain that the best option is to play to your strengths, making the decisions around what resources you have available, for how long, and the skillset encompassed within.

I will consider this approach in future projects, but as for it’s success, only time will tell.

23. October 2014 by Adam Riddick
Categories: Design & Practice | Leave a comment

SSRS Performance with Option(Recompile)

Sometimes, SQL Server isn’t as great as it usually is and can cause SSRS Performance issues when running queries that execute fast inside SSMS.

Just the other week I was writing a simple join script against close to 200k records in each of the 3 join tables. The script in question was for a report with a certain degree of complexity, meaning a lot of options and filter where being made available to those viewing the report. This in turn, meant a lot of variable parameters within the report query.

This report came with SSRS Performance issues. The query itself ran in less than two seconds inside SSMS, but gave up running after 4 minutes through SSRS.

Continue Reading →

15. October 2014 by Adam Riddick
Categories: Business Intelligence, SQL, Tips | Leave a comment

Sql Server Reporting Google Chrome Fix

Two weeks ago, I blogged about the need for Reporting Systems to support and influence the decisions being made by any organisation. Today, I’ll explore a Sql Server Reporting Google Chrome Fix, to enable the viewing of SSRS reports in the Google Chrome Browser.

In the article two weeks back, I mentioned the availability of many different reporting systems, from Sql server Reporting through to Crystal Reports. The organisations I have worked in have used one of these solutions, though have found more success with Sql Server Reporting. It’s no secret that Google Chrome is a popular browser, or that Sql Server Reporting doesn’t play nice with Chrome.

This is why we require a Sql Server Reporting Google Chrome Fix. And it’s pretty straight forward.

Continue Reading →

11. October 2014 by Adam Riddick
Categories: Business Intelligence, SQL, Tips | Leave a comment

Editable User Friendly URL Structure in MVC

User Friendly URL’s

There is a logic behind user friendly URL structures on a website. No matter what you call them, Clean, User Friendly, SEO Friendly, or Semantic URL’s, the purpose behind them is to improve a website experience by ensuring the website URL’s maintain an intuitive meaning amongst non-expert end user’s.

I’ll explore this in a little more depth.

Considering the above two URL’s, it’s clear to see the latter user friendly URL has a much clearer meaning to the user, and can potentially be easily altered, in a breadcrumb manner, to easily navigate the structure of your website.

Imagine trying to edit the first URL to show trainers instead of loafers, wouldn’t know where to start right?

Continue Reading →

02. October 2014 by Adam Riddick
Categories: ASP.Net, C# | Leave a comment

← Older posts