Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

Thursday, July 30, 2009

Generating PROXY from interfaces (Using Reflect Emit) : The flexible way to reduce code

Whats is a Proxy
A proxy is a class object, that acts as the original class type. Lets assume we have an interface ICustomer and we need to get implementations of this interface from different datasources (XML, flat file, soap object). Before we could assign data to the instance of this interface, we need a concrete type that implements the interface i.e XMLCustomer implements ICustomer . If what we need is to represents what is defined in the ICustomer interface, then we do not need the extra type XMLCustomer instead we will make a proxy from the interface, i can hear you say why, well, read on .....

I have been doing a lot of code reduction lately, in fact all my years as a software engineer, i have been seeking ways to make development a happy hour for myself and my peers. Tell you what, domain driven development is the future of wring software components that is fail prove, it is also the future that will bring us closer to the market place.

Interface is a very powerful programming construct which reduces dependencies between applications and components. With interface, your code is not far away from TDD (Test Driven Development) and you can test first before writing any code. So if we want to write a code that is targeted at the future, we need to focus on interface.

Much blabbing, how do i generate proxy from interface

Here, i will be revealing some powers of the Reflection.Emit namespace of the .NET framework. Using components/classes of this namespace, will allow you to programmatically examine types and creating code at runtime, what we are going to do in this section is runtime code injection and code generation.

Now back to our ICustomer interface, let us assume the class definition is as follows :


public interface ICustomer
{
string FirstName {get; set;}
string LastName {get; set;}
}


Yep, the example above is very simple, we will use this in our PROXY generation pattern. Did i just here you say where is the class that will implement this interface, nope is the answer, there is none for today because we are trying to avoid more code.

Now The PROXY Maker

We would like to do something like the following :


ICustomer customer = PROXY.CreateProxy();


yep, this is cool, we do not have an implementation class, but our proxy maker creates one for us behind the scene while examining the structure of the interface ICustomer.


public class PROXY
{
internal const string VIRTUAL_ASSEMBLY_NAME = "our.proxy.us";
const string version = "1.0.0.0";

static AssemblyName assemblyName;
static ModuleBuilder moduleBuilder;

static AssemblyBuilder assembly;
static AppDomain curAppDomain;
static IDictionary cache;

static PROXY()
{
assemblyName = new AssemblyName(VIRTUAL_ASSEMBLY_NAME);
assemblyName.Version = new Version(version);
curAppDomain = Thread.GetDomain();
assembly = curAppDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
moduleBuilder = assembly.DefineDynamicModule(VIRTUAL_ASSEMBLY_NAME);
cache = new Dictionary();
}

private static ModuleBuilder ModuleBuilder
{
get { return moduleBuilder; }
}

public static T CreateProxy()
{
if (!cache.ContainsKey(typeof(T).Name))
{
TypeBuilder proxy = PROXY.ModuleBuilder.DefineType(typeof(T).Name, TypeAttributes.Class | TypeAttributes.Public, typeof(Object), new[] { typeof(T) });
proxy = Emit(proxy);
Type type = proxy.CreateType();
cache.Add(typeof(T).Name, type);

return (T)Activator.CreateInstance(type);
}
return (T)Activator.CreateInstance(cache[typeof(T).Name]);
}

private static TypeBuilder Emit(TypeBuilder proxy)
{
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
FieldBuilder field = proxy.DefineField(string.Concat("_", propertyInfo.Name), propertyInfo.PropertyType, FieldAttributes.Public);
PropertyBuilder propertyBuilder = proxy.DefineProperty(propertyInfo.Name, PropertyAttributes.HasDefault, propertyInfo.PropertyType, new[] { propertyInfo.PropertyType });

if (propertyInfo.CanWrite)
{
MethodBuilder setMethod = proxy.DefineMethod("set_" + propertyInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, null, new[] { propertyInfo.PropertyType });
GenerateSetMethodBody(field, setMethod.GetILGenerator());
propertyBuilder.SetSetMethod(setMethod);
}

if (propertyInfo.CanRead)
{
MethodBuilder getMethod = proxy.DefineMethod("get_" + propertyInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.HasThis, propertyInfo.PropertyType, Type.EmptyTypes);
GenerateGetMethodBody(field, getMethod.GetILGenerator());
propertyBuilder.SetGetMethod(getMethod);
}
}

return proxy;
}

private static void GenerateSetMethodBody(FieldBuilder field, ILGenerator iLGenerator)
{
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Ldarg_0);
iLGenerator.Emit(OpCodes.Ldarg_1);
iLGenerator.Emit(OpCodes.Stfld, field);
iLGenerator.Emit(OpCodes.Ret);
}

private static void GenerateGetMethodBody(FieldBuilder field, ILGenerator iLGenerator)
{
iLGenerator.Emit(OpCodes.Nop);
iLGenerator.Emit(OpCodes.Ldarg_0);
iLGenerator.Emit(OpCodes.Ldfld, field);
iLGenerator.Emit(OpCodes.Ret);
}
}


Now the deed has be done. We have the proxy class above using the Reflection.Emit, to emit code at runtime for our interface properties. For each properties defined in the interface, a method body is created for it in the proxy class

Thursday, August 28, 2008

Command Pattern as Workflow Pattern

In today's development efforts, we need to ensure that we write better code that really meet our demands, code that can be executed independent of another, code that are separated by what they do (Concerns), a pragmatic code that is very safe to execute (Reliability). An efficient code that handles all error proactively.

To write this kind of code, you need to start dwelling into design patterns or practices that will make life better for all of us. One of this pattern is what i will be discussing today (The Command Pattern). The command pattern as its name implies, is a practice of encapsulating chunks/subsets of operation/workflow into a reusable format that can be used independent of the environment it was called. Command Pattern From Do Factory Website

A typical scenario is this : You are writing a webservices that want to execute the following dependent operations as an atomic operation :

Get details of products/services
Calculate The Payment due.
Make Payment. By calling external webservice (Like payment Gateways).
Update Your Lagacy application.

A good look at the cases above should tell us that these operations will be executed within the CallContext of a method. You can imagine how bulky and spaghetti the underlying code will be, and i can see many if statements, many try catch blocks, many many code horrors. Anyway, let us take another look and approach on the problem on ground, what if we make the processes that we discussed above as a single unit that depends on the statuses of one and other.
As a single Unit we can have the following :


ProductServiceCommand
CalculatePaymentCommand
MakePaymentCommand
UpdateLegacyCommand


The following commands can be written in separate classes, that means that they can stand alone. Before i continue further with this design practices, i will now introduce the Command pattern by introducing the base class below:


abstract public class BaseCommand
{
CommandReciever commandReciever;

public BaseCommand(CommandReciever commandReciever)
{
this.commandReciever = commandReciever;
}

protected CommandReciever CommandReciever
{
get { return commandReciever; }
}

abstract public void Execute();
}


The class above marks the structure/template of our commands, all commands will inherit from this class, and they will override the abstract Execute method. All command will share one instance of a status object or Reciever object (In our context, it is CommandReciever). This object will be used to share information among commands. For example, we may want to check the status of CalculatePaymentCommand before we execute the MakePaymentCommand. If the calculate payment command fails, instead of returning/throwing an exception, we can simply return a status that the other commands can consume. Let us assume that our status is as follows :


public class CommandReciever
{
public CommandStatus ProductStatus{get; set;};
public CommandStatus MakePaymentStatus{get; set;};
public CommandStatus PaymentStatus{get; set;};
public double Amount{get; set;};

public CommandReciever()
{
productStatus = CommandStatus.NOTSET;
makePaymentStatus = CommandStatus.NOTSET;
paymentStatus = CommandStatus.NOTSET;
}
}

public enum CommandStatus : int
{
NOTSET = 0,
OK = 1,
FAILED = 2,
PAYMENT_SUCCESSFUL = 3,
PAYMENT_SERVER_ERROR = 4,
PRODUCT_UPDATED = 5,
UNSUCCESSFUL_PAYMENT = 6,
MAY_CONTINUE = OK,
MUST_DISCONTINUE = FAILED,
}


The commandReciever above will be shared amoung commands, so that state information of other comman can be seen across through the commandReciever object. Now let us delve into implementing our Commands : The following code blocks is the structure of our commands, in our case, i will be describing only one for space and readability on this post:


public delegate void StatusChangedEventHandler(object source, EventArgs e);
public class PaymentCommand : BaseCommand
{

public event StatusChangedEventHandler paymentStatusChanged;

public PendingPaymentCommand
(CommandReciever commandReciever): base(commandReciever)
{

}

public override void Execute()
{
if(commandReciever.ProductStatus.OK)
{
//Execute Payment Command Here.
}
}
}


The class above is a simple template of how the class structure of our commands will be implemented, so let us assume that all other commands inherit from BaseCommand and all commands have a constructor that takes an instance of commandReciever as argument. Also our assumptions is that, they all implement the Execute method.

Now that we are clear about how our four Commands will be implemented, then we will do the calling as follows :


CommandReciever commandReciever = new CommandReciever();
ProductServiceCommand productCommand = new ProductServiceCommand(commandReciever);
CalculatePaymentCommand paymentCommand = new CalculatePaymentCommand(commandReciever);
MakePaymentCommand makePaymentCommand = new MakePaymentCommand(commandReciever);
UpdateLegacyCommand updateLegacyCommand = new UpdateLegacyCommand(commandReciever);


The initialization code above can be used as follows :


productCommand.Execute();
paymentCommand.Execute();
makePaymentCommand.Execute();
updateLegacyCommand.Execute();


At last we have successfully separated each command as workflows that can be executed independently or as a unit of operation. Since commands share statues, a command will check if its other commands have executed successfully before it executes. Commands can also register events on one and other, so we can have some command registering themselves as a listener to a command for status change event notification. There are many usages of the command patterns, this is just one i have explained (Command pattern used as Workflow pattern.( Enjoy patternising).

Command architecture and dependency injection

On a recent project, we were mapping commands to user intentions, covering all aspects pertaining to the usage of the application from the p...