Wednesday, February 10, 2010

C# Design Patterns: Factory

What is the factory design pattern? Well to begin with it is something that is referenced frequently in software architecture. Functionally, a factory builds an object. More specifically, factories render instances of an abstract class type.

C# Example

How often have you got caught up in creating objects based upon business logic? Something like this:

 public interface ICar
{
 decimal Price {get;set;}
 int HorsePower{get;set;}
}
//found somewhere randomly in your code...
 ICar result;
 //this code is heavily biased
 if(user.IsRich)
  return new AstonMartin();
 else if(user.IsSteelWorker)
  return new Ford();
 else if(user.IsPractical)
  return new Honda();
 return MomsCar();

I've found code like this in projects many times and have done it myself. What's really wrong with this?

  1. If you need this code again, and copy/paste, you'll be violating DRY (do not repeat yourself)
  2. Not reusable
  3. Not centrally based, so a change in one place will need copied to another
  4. Whatever class this code is in is at this point violating the Single Responsibility Principle

The Factory Design Pattern Fix

Take a look over why this is architectually better:

public enum CarTypes { NotSet, Honda, AstonMartin, Ford };
public sealed class CarFactory
{
    public ICar Create(CarTypes cType)
    {
        if (cType == CarTypes.Honda)
            return new Honda();
        else if (cType == CarTypes.AstonMartin)
            return new AstonMartin();
        else if (cType == CarTypes.Ford)
            return new Ford();
        throw new ArgumentOutOfRangeException("cType");
    }
}

What have we changed in this example?

  1. All of our code is in one area--easy to update and reuse
  2. The factory is sealed, so we need not worry about any other classes changing the factory behavior

Simple stuff!

Monday, February 1, 2010

Dependency Injection in .NET

I'm really on an architecture kick at this point. Honestly, it's probably about time. I find few senior-style job postings that do not ask for some knowledge of Spring.NET or Castle Windsor. Now that i've done a little reading up on the subject, I see that this is for good reason.


Introduction: What is Dependency Injection?


This stuff is tricky--I'm not going to lie. First of all, I would recommend reading up on the basics. Until you start to really see the power behind defining interfaces and working with abstractions dependency injection will be unnecessary for you.


Dependency Injection strives to decouple classes from dependencies. For instance:


public interface IComplaintHearer
{
void RegisterComplaint(string message);
}
public class Manager : IComplaintHearer
{
public Manager() { }
public void RegisterComplaint(string message)
{
//do something with message
}
}
public class Employee
{
//completely dependent upon this exact class
private Manager _itsManager;
public Employee() { }
public void Complain(string complaint)
{
_itsManager.RegisterComplaint(complaint);
}
}

What's the issue? What if we want the employee to report to someone other than its immediate boss? Or, what if we want the employee to complain to a co-worker? We would have to completely change the class. Right now this code completely violates the open closed principle(among others) we discussed when reviewing the S.O.L.I.D. principles. So lets use the dependency inversion principle and make this class dependent upon an abstraction:


public interface IComplaintHearer
{
void RegisterComplaint(string message);
}
public class Manager : IComplaintHearer
{
public Manager() { }
public void RegisterComplaint(string message)
{
//do something with message
}
}
public class Employee:IComplaintHearer
{
//completely dependent upon this exact class
private IComplaintHearer _complaintHearer;
public Employee(IComplaintHearer hearer)
{
_complaintHearer=hearer;
}
public void RegisterComplaint(string message)
{
//do something with the message
}
public void Complain(string complaint)
{
_complaintHearer.RegisterComplaint(complaint);
}
}

And we would need to run this code like so:


//we could pass a manager, or another employee if we wanted to
Employee myEmp = new Employee(new Manager());

Injecting the Class, Instead of Providing It


Imagine a scenario where we had tons of classes that implemented the IComplaintHearer interface. We'd have to recompile the code everytime we want to change who the employee complains to. This is where a dependency injection steps in and allows you to:


  1. Specify a class's dependency at run-time
  2. Dynamically use classes in another assembly
  3. Make changes without recompilation

Let's take a look at an example:


public interface IComplaintHearer
{
void RegisterComplaint(string message);
}
public class Manager : IComplaintHearer
{
public Manager() { }
public void RegisterComplaint(string message)
{
//do something with message
}
}
public class Employee:IComplaintHearer
{
//completely dependent upon this exact class
private IComplaintHearer _complaintHearer;

//use the IComplaintHearer subclass that the Dependency Injection Framework (StructureMap in this case) tells us to
// this depends upon the xml that defines what to use (below)
public Employee(): this ( ObjectFactory.GetInstance()){}
public Employee(IComplaintHearer hearer)
{
_complaintHearer=hearer;
}
public void RegisterComplaint(string message)
{
//do something with the message
}
public void Complain(string complaint)
{
_complaintHearer.RegisterComplaint(complaint);
}
}





What just happened? By using the StructureMap Framework for .NET, we just specified the IComplaintHearer that our employee class will default to--the manager. In the XML above, we mapped the expected type/assembly to the default type/assembly. Further, we could set up defaults for all of our classes that we could change later without ever having to change any code. In some ways, I feel like this is moving a problem from one environment to another, but in other ways i think it is a great architectural tool.


What do you think?