Friday, August 29, 2008

.NET Primitive Wrapper Classes Where are thou?

In my day-to-day experience with code, forum users, other developers, i have been asked this question (Wrapper classes for primitive type) a thousand times before and now. Most developers especially the one's coming from Java Land (Like me, i am a Java Lander and still i am) seems to bring with them the Jar of Java coffee, and when they successfully arrive NLand, they realize its a different ball game here, because NPeople are not coffee drinkers, they are business men. Lets cut the story of N and J short, because the similarity and the dissimilarity of both lands is what makes them different.

We will not argue about the two lands today, but try to work around a simple primitive Wrapper for int, lets call our wrapper BigInteger or Integer (I will choose Integer or something like IntegerWrapper since .NET people may want to include Integer class as part of the base class libraries in the upcoming and not so far future. In Java, int is mutable because you are allowed to change the value of int anywhere in your code.

In Java we have several Wrapper classes which i will like to metion below, they wrap-up primitive data - types and have an object representation of it. The following class are some of the primitive wrapper classes in Java.

  1. BigDecimal
  2. BigInteger
  3. Byte
  4. Double
  5. Float
  6. Long
  7. Integer
  8. Short
All of these wrapper classes described above inherit from an abstract class called Number (You can sense some intuitiveness of java here). So in java, a primitive integer type can be used as follows :


int value = 200;
Integer bigInt = value;
value = bigInt;


Although wrapping and un-wrapping or autoboxing and unboxing (NLand calls it Boxing and UN-Boxing. But to object) primitive data types has a performance implications, but there are some situations that we cannot do without them. So how to we bring this type of functionality to .NET, how do we ensure that our primitive types can be treated as a reference type. First let me point out some few facts about what we have in the .NET API (Application Programming Interface).

Boxing and UNBoxing

Well, with the little approach we described above, we can fully understand that in .NET we have the term boxing and unboxing. This allows us to use an value type as an object and re-casting the value type from an object to its primitive state : The following is valid :


object value = 200; //Store an integer
int intValue = (int) value; //returns the value 200 to an int via type casting. It
is not automatic casting.


The above snippets shows how we can do boxing and unboxing in .NET, but where is the performance implications in this? of cos there is, when you cast a primitive type to object in .NET, an reference is allocated in the garbage-collected heap, that means an object memory is allocated for it. Let us take another simple approach :


object value = 200;
object value2 = value;

value2 = 500;
value still remains 200.


The code above retains the content of value and creates a new object in the memory heap when we assigned value to value2. We would have thought that the two objects would have a reference to a single object in memory, but the data is duplicated. So we need to be carefull when dealing with boxing amd unboxing this way.

Also we can use the System.ValueType class, which is the base class for all .NET value types, still this approach does not guarantee type safety and and it encourages more type casting and also incur the performance implications as the boxing and un-boxing approach.

So what are we going to do?

we are going to create a custom Integer Wrapper for .Net, and we will ensure that it is used like its java counterpart. So here our code goes :


public class Integer
{
int value = 0;

public Integer(int value)
{
this.value = value;
}

public static implicit operator Integer(int value)
{
return new Integer(value);
}

public static implicit operator int(Integer integer)
{
return integer.value;
}

public static int operator +(Integer one, Integer two)
{
return one.value + two.value;
}

public static Integer operator +(int one, Integer two)
{
return new Integer(one + two);
}

public static int operator -(Integer one, Integer two)
{
return one.value - two.value;
}

public static Integer operator -(int one, Integer two)
{
return new Integer(one - two);
}
}


The code above is a representation of the Integer wrapper class in java in .NET. So, having created our class above, we need to see how we can utilize it. Below is how we can make use of it.


Integer integer = 345;

integer = 10 * 11;

int value = integer;


Now we have our a reference type for integer type in .NET. Note, you can overload other operators to make sure your reference type can be used with other operators. Enjoy your Wrapper.

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).

Friday, August 15, 2008

Persistent Ignorance. Is that another acronym

Gone are the days that we couple our data access code within our business layers/logics., the days of manually writing SQL scripts is over and stored procedures are becoming un-popular in Object Oriented Programming because the paradigmn is shifting from data cetricness to object focuseness. We write code in the modern day using modern tools and languages like C#, Java, Smalltalk, C++ etc These platforms or languages follow common design structure which is termed as object orientation. With the fact that we use OOP, we always want to use the OOP semantics in our coding culture, analysis, and software designing.

In other to separate data from OOP,
we have seen the birth of many ORM frameworks (Object Relational Mapping) and code generations and yet there are still many on born frameworks comming into play very soon. Soon we will feel the quantum leep from data centeredness to object orientation. As part of the shift in paradigmn, we saw the birth of AOP (Aspect Oriented Programming) yet many are coming.

Our focus today will be about Persistent Framework and how the industry have tried to make them persistent ignorance. For those who dont understand, persistent ignorance is the ability of our domain model to be ignorant of our persistent framework. The following code is not persistent ignorant :

public class Foo : IPersistable;

The class Foo above, is a domain entity class, but it is forced to implement IPersistable because its a requirement by the underlying persistent framework. If you want to change persistent farmeowork then the problem comes, you will change so many code to make your class compliant to the new persistent farmework.


M
ost Persistent Frameworks are not Persistent Ignorant, how do we plan for cross ORM frameworks, when we decorate our entities with attributes, we must implement IBigBoss, we are forced to make our POCO or POJO abstract, we use mapping xml file that are embedded into our assemblies (The XML approach is the father of couping because It goes with our transparent POCO'S as embedded resource. This does not allow for Refactoring with the range of refactoring tools we have today).

As we proceed,with the chaotic nature of our industry, we realize there is no silver bullet, even though we longed and waited for the miracles to happen, some of us have realized that we cannot wait forever, something need to be done, that is where Open Source framework comes into play, and different types of AOP (Aspect Oriented Programming) framework's filled the whole programming community.

Recently, i am searching for a Persistent Ignorant ORM Framework, and i realiazed that there is none, even if there is any, the framework will be descriptive [Meaning that you must obey the do's and dont's].

There have been several long debates going on in the Object Persistent Industry, but there havent been a silver bullet, and there wont be any. Relational is not Object period. So we still need a way to tell the Persistent Engine how the transformation will be done. If Microsoft claims to give us such functionality without the use of Visual Studio to hide the intricacies of the mapping, we are ready to sing the "oh happy day".

Most of us (The developers, Analyst, Architects etc) are the root causes to what is happening to software engineering today, we always want a rocket scince, something that cannot be done without plumbing, but have we forgotten that even the JVM's OR CLR's of today is hiding somethings away from us if not, why cant we all start programming in Bytecode or IL or ILasm. Even OOP have its own semantic's which we must follow, if we must use the language. So i wonder why we cannot live by the semantics of ORM mapping and yet we ask too much of the framework.