Monthly Archives: May 2013

Factory Pattern

When we are designing systems we can make use of a variety of deign patterns. They are valuable for many reasons, not least that using a common and understood way of designing something means that it will be easily understood by people familiar with the pattern.

The Factory Design pattern can be used when you have a large number of similar objects (so can be referred to through a common interface or abstract class), and where you wish to hide the instantiation logic from the calling class.

Consider a simple drawing program. You might want to create one of a large number of types of shape, square, circle, triangle etc.

We can use a Factory class to return an instance of the type of shape we want:


public abstract class Shape
{
  public abstract Shape createShape();
}

public class Square : Shape
{
  public Square() {}

  public override Shape createShape()
  {
    return new Square();
  }
}

public class ShapeFactory
{
  Dictionary<string, Shape> registeredShapes;

  private static readonly ShapeFactory instance = new ShapeFactory();

  private ShapeFactory()
  {
    registeredShapes = new Dictionary<string, Shape>();
    var Shapes = from b in Assembly.GetExecutingAssembly().GetTypes()
                 where b.IsSubclassOf(typeof(Shape))
                 select b;

    foreach (var type in Shapes)
    {
      var s = type.GetConstructor(System.Type.EmptyTypes).Invoke(null);
      registeredShapes.Add(type.Name, (Shape)s);
    }
  }

  public static ShapeFactory Instance
  {
    get
    {
       return instance;
    }
  }

  public Shape createShape(string shapeName)
  {
    return ((Shape)registeredShapes[shapeName]).createShape();
  }
}

From this we can simply call ShapeFactory.Instance.createShape(“Square”); and this will give us a new instance of the Square object.

As we expand to define extra types of shape, we won’t need to alter the Factory, we can just implement the new shape, it will be discovered automatically, thanks to the use of reflection.

Whilst this is clearly a simple example, where we are just creating and return the objects, it should be easy to see that we can use much more complicated objects. We would hide all the creation logic inside each type, and use the factory to pass an fully created concrete instance whenever one is required.

Advertisements

Azure – An Exploration

Microsoft’s cloud offering is known as Windows Azure, and it is rapidly maturing. A couple of years ago it was clunky and hard to use, now it integrates quickly and easily with Visual Studio, making creating and deploying scalable cloud applications quick and easy.

There’s a free trial for new users, and those of us lucky enough to have MSDN subscriptions  get a certain amount of compute and data space for free. You can run a number of websites at a free pricing tier, but for anything complex or customised, you will have to pay.

I’ve created a simple application, Magic Deck Statistics Viewer, to get a fuller understanding of Azure, and how it all fits together. My application collects information about decks used in the popular card game Magic: the Gathering, and allows users to generate charts based on the collected data.

It uses a single worker role to gather data once a day, and two web roles to manage the actual site. It’s developed in ASP.NET MVC4, using Visual Studio 2012. I make use of the Extra Small compute instances. These are very cheap to run (you can manage 8-9 on an MSDN subscription), and allow practice with the features of Azure without running up a large bill.

I’ll be covering the details of my Azure Exploration in further posts, and hopefully it will prove to be useful and enlightening to those just starting to investigate the cloud.

 

 

Interfaces and Abstract Classes

In .NET we can think of Interfaces as a contract for behaviour.

Any class that implements the Interface will be required to implement all of the methods defined in the interface. An Interface can only have a list of methods to be implemented by inheriting classes, it can contain no implementation detail.

A class can implement many Interfaces.

Interfaces can be used by many kinds of class. You might create an IFlyable interface, with a single method, Fly. This could be implemented by a Plane class, a Helicopter class a Bird class and so on. There is little to link these class types, but they all Fly.

An abstract class is similar to an Interface, but has a number of important differences. Where we consider the Interface as a contract for behaviour, an abstract class will define what a set of objects is.

An abstract class would be a base for many similar classes. It can contain methods and state data that cannot be captured in an Interface. You could create an Animal class, and contain properties for Height and Weight. You could also add a method Breathe, which would cause the animal to breathe. In the Animal class you can have a simple implementation of the Breathe method, and you can override it in complex child cases (such as a Fish class).

A class can only inherit from a single abstract class.

So, Interfaces describe what an object can do, abstract classes describe what an object is.

Sql Standard Joins

When you need to get sensible data out of a well designed database, you will often need to use a JOIN condition.

JOINs will join together two (or more) tables, based on the columns that you select. The two most common types of join are the INNER JOIN and LEFT OUTER JOIN.

An inner join will return rows from the database that match on both tables referenced in the join. A left outer join will return all rows from the first referenced table (the left), and include matching data from the second table.

As a simple example, imagine we had a table containing the details of some Invoices, and a table with details of the Line Items on each invoice.

In a realistic schema we’d have further tables for Customers, Items and so on, this is kept deliberately simple for illustration purposes.


InvoiceID   InvoiceDate   Customer

1           2013-05-01    John Smith

2           2013-05-03    Mike Philpott


LineItemID   InvoiceID   Item       ItemPrice   Quantity

1            1           No6 Bolt   0.54        20

2            1           No7 Screw  0.31        10

With these two very simple tables, we can see the syntax for both types of common join, and also what records would be returned.


SELECT
    InvoiceDate, Customer, Item, ItemPrice, Quantity
FROM
    Invoices
INNER JOIN
    LineItems
ON
    Invoices.InvoiceID = LineItems.InvoiceID

This will return only the two rows for John Smith’s order, Mike Philpott’s will be excluded, as it has no line items


SELECT
    InvoiceDate, Customer, Item, ItemPrice, Quantity
FROM
    Invoices
LEFT OUTER JOIN
    LineItems
ON
    Invoices.InvoiceID = LineItems.InvoiceID

In this case, we will see three rows, two for John Smith, with full items details. The third will show Mike Philpott’s order. It will contain values for InvoiceDate and Customer, but will have NULL in Item, ItemPrice and Quantity, as there are no matching rows in the table that is used.

We can expand the joins to consider further tables, by using additional blocks of JOIN and ON. Be careful that when you do this your joins are ordered correctly, so that the appropriate tables are considered at the right time. If the order is incorrect, an INNER JOIN may be applied to the results of a LEFT OUTER JOIN, when you intended the INNER JOIN to be applied first.

In summary, we should use INNER JOIN when we only want to know about the rows that have matches in the linked table, and the LEFT OUTER JOIN when we want to retain all rows in the first table.