Enabling change by hard coding everything: the smart way

time to read 3 min | 470 words

Okay, hopefully this post has caused enough interest in the subject. Let us explore what I said:

I consider hard coding as much as possible as a key concept in enabling change.

The first part that you need to notice is "as much as possible". This is another way of saying YAGNI. That is, if you don't really need it flexible, just hard code it. JFHCI is my new motto. When accepting an order, we want to give 5 percent discount for preferred members. How are we going to handle this scenario?

We will hard code it!

public void SumbitOrder()
{
	if ( User.IsPrferred ) 
		AddDiscountPrecentage(5);
	// do other interesting stuff
}

Oh, you also need to change that? Bummer, I guess we can't hard code this. And at this point, the typical reaction is usually one of the following:

  • Let us go with a rules engine!
  • Let us build a DSL!
  • We should write a framework!
  • Put it in XML!

From the tone of this post, you can probably understand that this is not something that I am going to suggest. I am going to suggest that we will still should hard code it. But this time, we should hard code it in a smart fashion.

It is easier to show the code than to explain:

public class DiscountPreferredMembers : OnOrderSubmittal
{
	public override void Execute()
	{
		if ( User.IsPreferred )	
			Order.AddDiscountPrecentage(5);
	}
}

As you can see, the business rule is still hard coded. But now we also have a structure to it. With just a tiny bit of infrastructure, we can take this code and start adding other interesting aspects to it. Deploying a DLL containing this class to a specified folder will automatically pick it up and run it at the appropriate times.

Our solution is incredibly simple. We hard code the rules, which is the easiest approach to getting things done. Because we have a structured way of doing that, we can now apply the ways in which we use it. For instance, if we wanted to support runtime replacements of rules, that is easy, all we need to do is to provide a FileSystemWatcher and reload them. If we want to add a rule, we just create a new class for that. If we want to modify a rule, we go and change the hard coded logic.

This post and the previous ones has been intentionally written in a somewhat inflammatory fashion. I want to encourage people to get used to thinking about things in the simplest possible way. Embrace hard coding, it will make your life easier.

Readability is improved, testing is easy, maintainability is a snap.

Just hard code it!