Something, something, … Refactor!

This blog has moved, you should read this at my new place!

Many of us developers leave for work on a daily basis, ready to throw ourselves onto the next change request that will change the world as we know it, only to find yourself hack ‘n’ slashing through a jungle of WTF’s, copy-paste inheritance, awfully named fields, and more WTF’s.

This probably sounds like a broken record to you, and though I could go on all day presenting you with examples, I’d rather suggest an alternative: Refactoring.

Refactoring is a word mostly spoken in the domain of TDD, from its well known mantra “Red – Green – Refactor”.  However, refactoring does not belong exclusively to the exotic world of TDD, which can spark fear in the minds of many developers not familiar with TDD.

Refactoring has been the topic of many books, and rightfully so. The list of possible refactorings is a long one, but many of these techniques are really quite simple.
And more importantly: it can significantly improve your code base.

Yes, refactoring can improve readability and flexibility, which in turn improves maintainability. Improved maintainability leads to less money spent on fixing bugs, which leads to happy customers, which leads to less picking on us poor developers, a more satisfying job and ultimately: improved health by reduced stress. See that? All benefits! =)

When done, refactor

So why do we write less readable, less flexible code than we possibly can?

With deadlines and project managers breathing down our neck, it is easy to conveniently forget the refactoring part and move on to the next task at hand. We hope to never see that piece of code again, or think that the code we just wrote is “pretty ok enough” to understand 6 months down the line ( hint: it isn’t ).

So when you’re leaving the campground, be sure to leave it cleaner than you found it, and clean up after yourself. Start off by asking yourself the following simple questions:

–          Could my field names be any more meaningful?
–          Are my method names truthful? ( ie: don’t lie )
–          Do I repeat myself unnecessarily?
–          Does my code need any documentation? ( answer = yes )
–          Do I still need that piece of commented code? ( answer = no )
–          Could any other developer read this code and on sight understand what it does?

Contemplating about these things alone can be the first step towards a cleaner codebase and a happier life in code, knowing you’ve become a better developer. Next time you have to change something in that particular code file, you will thank yourself you took 5 minutes to clean up.

So while you’re at it, why not also improve your codebase with:

–          Checking if your code is SOLID?
–          Programming to interfaces instead of implementations?
–          Writing meaningful tests?

There are so many other things you can do to improve your code. Keep reading about ways to code better, and remember to refactor and clean up your code whenever you’re done with a little piece of code.


Even if you won’t have to maintain your code in the future ( never say never ), clean up your code when you’re done with it, even if it’s just for good programmer’s Karma and the next guy that might have to maintain it.

Stay realistic: your code will never be perfect. But writing bad, cluttered or unreadable code willingly or knowingly should never be an option, and since you have read this post, you now no longer have any excuse. 😉


Code Contracts Static Checker: Best practices & guidelines

This blog has moved, you should read this at my new place!

As stated previously, Code Contracts can give you certainty that your classes behave exactly in the way you want them to.
By defining pre- and postconditions on them, you can tell what you expect from a certain class and what others can expect from your classes.

A number of posts and concerns about Code Contracts revolve around the static checker, and how to make it prove that certain contracts are correctly followed.
Sometimes this can be quite challenging, though I see this more as a pro than a con.
Making you think twice (or more) about your code is never a bad thing, really.

But for those who desperately seek salvation in their quest to annihilate all static checker warnings ( with or without Contract.Assume() ), I would recommend the following guidelines:

1. Install the Code Contracts Extension for Visual Studio 2010.
2. Use Reflector to see Code Contracts on the Base Class Libraries.
3. Use Pex to automatically test your methods.
4. Split more complicated statements into multiple lines.

1. Code Contracts Intellisense.

Install the Code Contracts Extension for Visual Studio 2010. This brings contracts right to your Intellisense as you type, as well as some other handy features.

2. Use Reflector to see Code Contracts on the Base Class Libraries.

When you use the static checker, you might notice that a lot of methods in the BCL already have contracts defined on them. For example, the IList.Clear() method has a postcondition stating that the Count property will be equal to zero.

These contracts are not magically inferred from the BCL assemblies, but rather found in the Contract Reference Assemblies that are included with the Code Contracts installation. These assemblies are found under <%YourProgramFiles%>\Microsoft\Contracts\Contracts\.NETFramework\v4.0.

Code Contracts BCL Assemblies

Code Contracts BCL Assemblies

Using Reflector you can browse through these assemblies, which contain nothing but Contracts. Although a lot of methods already have contract defined on them, the BCL contract assemblies still have a lot of contracts missing.
Using Reflector on these assemblies, you can find out for yourself why you keep getting a warning that a certain “contract cannot be proven”.

Code Contracts String.Format in Reflector

Code Contracts String.Format in Reflector

3. Use Pex to automatically test your methods

Pex provides a way to create parameterized unit tests to see which input causes your method to violate a contract. Actually, it does a lot more than that. Way too much to elaborate on in this post.

To make a long story short, Pex can automatically unit test your parameterized methods with different kind of inputs ( without resorting to brute-force). What’s great about this, is that it works in combination with Code Contracts, and can actually suggest contracts for you.

The documentation pages includes a nice tutorial on how to use the power of Pex in combination with Code Contracts.

4. Split more complicated statements into multiple lines.

Although simple, quite effective.

A lot of concerns surrounding the static checker’s inability to prove something are easily solved by this one. Some developers have the tendency of joining multiple statements in one big statement. This can improve readability and shorten your code files, but also confuse you about which statement the static checker is complaining about.

Split your big statement into several lines, and it will become more clear which method the static checker is complaining about.

For example:

StringHelper.CleanUrl( new PageManager(“BasePage.aspx”).GetFullUrl()) ;

has a lot of places where there could be a nullreference occurring. Splitting this into several statements would make this a lot easier for you to see what method gives you the problem. ( This is actually general debugging advice, not just for the static checker )


A lot of static checker warnings will easily be solved by following one or more of the solutions provided here, others will require more digging through your own code. There will be times when you will still need to Assume some conditions, as the static checker will never be able to statistically proof every line of code you write.

However, hopefully these guidelines will aid you in proving your contracts to the static checker, further improving your code base with better documented behavior, promises and expectations.

New Code Contracts Extension: See Contracts in Intellisense

This blog has moved, you should read this at my new place!

Code Contracts just got a whole lot better with a brand new extension for Visual Studio 2010!

This new extension brings a couple of cool new features that help you while developing with Code Contracts.

See contracts as you type

Just start typing a method with contracts, and they will be listed right beneath the description of the method.

The great thing about this is that it works for methods in the BCL as well as your own methods.

See inherited contracts

Contracts that are inherited show up above your methods. It’s a helpful visual reminder of the contracts that are defined on the interface or class you’re inheriting from.

This way you can easily add preconditions and postconditions without having to look back and forth to see which contracts are already defined.

And it doesn’t actually add text to your code file, it’s just an adornment which you can easily click away too.

See contracts for external assemblies

Another helpful addition is being able to see contracts of external assemblies. The contracts are visible in the metadata file you see when you ‘go to definition’ of a member of a class of which you don’t have the source.

This can also be disabled by a simple click of a button labeled “Hide all contracts” ( See, it’s all obvious ).


Before this extension, visibility of the contracts was one of my major concerns with Code Contracts. Not being able to see contracts as you type made you rely on the static checker to see what contracts were defined on your code. This extension is a great improvement and incentive to using Code Contracts. It’s only just released, but I’m loving it already!

Great! So how can you have a piece of this?

It’s easy!

  1. Install the latest version of Code Contracts
  2. Install the Code Contracts Editor Extension for Visual Studio 2010.
  3. Enable Code Contracts and choose ‘Build’ for ‘Contract Reference assembly’ in the Code Contracts properties pane.
  4. Build your code

And you’re ready to see your contracts showing up as you type! Have fun =)

Code Contracts: Is the static checker really that thick?

This blog has moved, you should read this at my new place!

When you start working with Code Contracts, you often get the feeling that you have to add contracts everywhere for everything. When you enable the static checker on an existing project, you might get a lot of warnings.

A lot of these

A lot of these

Something that troubles starting users is the fact that you have to add a lot of contracts ‘twice or more’. I’ve recently seen this issue appear on stackoverflow as well. You can check out the specific code sample there, but I’ll lay it out for you here as well. Suppose you have a public method calling a private method, both of which accept an input parameter of type string.

public void ValidateString(string givenString)

    var isValid = SomeValidatingMechanism( givenString );

private bool SomeValidatingMechanism( string toValidate )
    return toValidate.Contains("someImportantValue");

I’ve immediately added a precondition to the ValidateString method, to make sure the caller never wrongfully provides me with an empty string and make my application crash to death.

Now when you let the static checker loose ( and you’ve set it to check for possible nullreference occurrences), it will whine about my private method calling Contains on a possible null value. What’s that all about? I added a precondition to the public method, so the toValidate string can’t be empty, right?


Well, actually the static checker is really thinking ahead here.

First of all you’ve got the static checker which cannot prove that the the toValidate string isn’t actually null. You know it, because you can clearly see from the code above. But the static checker cannot mathematically prove that you did not alter the toValidate string after it entered the public method. For all it knows, you might have maliciously set it to be null right after it entered the method, trying to crash my application once again! This might seem like a limitation to the static checker, but imagine you made some calls to an external API before you called the private method here. The static checker is just really playing it safe.

Secondly, for now you might have only one call to the private method, but what happens when you add more calls to it from methods which didn’t have a precondition like the one above? Adding a precondition to the private method now can prevent future errors and possibly lots of debugging.

public void ValidateString(string givenString)

    var isValid = SomeValidatingMechanism( givenString );

private bool SomeValidatingMechanism( string toValidate )
    return toValidate.Contains("someImportantValue");

With the above code the static checker’s warning is gone, and your code feels safer once again =) You can sleep tight and never worry about some co-developer calling your private method with an empty string.

So no, the static checker isn’t really that thick, it’s actually quite smart and following it’s advice can often lead to better and safer code.

Using Code Contracts to define behavior

This blog has moved, you should read this at my new place!

First: an introduction

Code Contracts is a language-agnostic tool that provides you the power of Design By Contract development. In short, it enables you to make statements about what your code expects and delivers. It’s a great way of telling whether or not your code does what you expect it to do.

Actions speak louder than words, so let’s bring in an example: the BankAccount class.

public class BankAccount
public decimal Balance { get; set; }
public double InterestRate { get; set; }

public void Withdraw(decimal amount)
Balance -= amount;

public void Deposit(decimal amount)
Balance += amount;

public void AddInterests()
var interests = Balance * (decimal)InterestRate;
Balance += interests;

A real simple class that should speak for itself. It maybe could use some comments, DDD or better logic, but it’ll do for this post.

Adding preconditions

Preconditions are a way to define what state your application must be in at the start of execution of a called method. They’re all about telling what you expect from someone calling your methods.

Let’s take the Withdraw method: someone withdraws money from their account. We might have the following expectations:

  • If you withdraw money, you should at least have money on your account.
  • You have to withdraw some money, which means more than nothing ( else it wouldn’t be really withdrawing, would it? ).
  • You aren’t allowed to withdraw more money than you have.

All of these expectations can easily be converted to preconditions in Code Contracts, by using the Contract.Requires method.

public void Withdraw(decimal amount)
Contract.Requires(amount > 0);
Contract.Requires(Balance > 0);
Contract.Requires(Balance >= amount);
Balance -= amount;

The nice stuff is that you’re not only defining the state your application must be in, you’re also defining behavior here.

Adding postconditions

Postconditions define what state your application should be when it leaves the called method. This is the part that’s all about delivering promises about your code, as well as checking if the method did what you expected it to do.

For the Withdraw method:

  • We state that after we withdraw money, the balance of the bank account won’t be negative.
  • We also state that after the withdrawal, the balance will be the starting balance ( when we entered the method ) minus the amount we withdrawn.

Once again, the postconditions are easily converted to contracts. The Contract.OldValue() represents the value of a certain field or parameter as they were in the beginning of the method.

public void Withdraw(decimal amount)
Contract.Requires(amount > 0);
Contract.Requires(Balance > 0);
Contract.Requires(Balance >= amount);
Contract.Ensures(Balance == Contract.OldValue(Balance) - amount);
Contract.Ensures(Balance >= 0);

Balance -= amount;

The second statement here seems pretty obvious because of the actual code following the contracts, but a lot of times this code will obviously be quite more complicated.

Isolating object invariants

Object invariants are conditions on an object which should be true at all times that object is visible to a client. They express the conditions under which the object is in a “good” state.

As good programmers we try to prevent writing the same code twice, and if we look at the preceded code we notice the balance must always be greater than zero.

For the balance to be in a good state, it must never be zero.

We can isolate this contract by creating a method that contains Contract.Invariant() statements, and decorate this method with the ContractInvariant attribute.

private void EnsureBalanceIsPositive()
Contract.Invariant(Balance > 0);

All the invariants will be checked at the end of every public method. So now we added these, we no longer need the preconditions regarding the balance being greater than zero.


Although this example uses really simple code, by using Code Contracts we made it exactly clear what this BankAccount can and cannot do.

Your code can become immensely more complicated, new developers can join your project but by defining the behavior of this class by contracts, they will immediately recognize what the class does.

Ideally we would define the contracts on an interface or base class, so deriving classes would all share a base behavior, but that’s out of scope for this post. =)

For more info on Code Contracts, visit the homepage here.

Calculating Routes in .NET: 5 minutes tutorial

This blog has moved, you should read this at my new place!

Calculating the ‘road distance’ between two points can come in handy when you want to calculate the transport costs between your company and your customers.

Google Maps is great for calculating a single route, but when you want things automated, you need some kind of web service for this, which Google doesn’t provide.

A lesser known competitor of Google Maps is Microsoft’s Bing Maps, which has a great SDK that you can get up and running in about 5 minutes, and 4 easy steps.

1. Create a Bing AppID

To be able to use the Bing Web Services, Microsoft requires you to request a unique key through this website ( you will need a Live ID ).

2. Add a Service Reference

Add the following service reference to your project:

3. Setting up your request

Next thing we do is set up the RouteRequest.

In this example I provide the latitude and longitude myself ( from a random geocoding site ), but you could use Microsoft Bing’s or Google’s geocoding service as well, to get the lat/long from any address you like.

I’ve added some commentary in the code, so it should be self-explanatory.

// Get a key at
string key = &quot;xxx&quot;;

BingRoutingService.RouteRequest request = new RouteRequest();
request.Credentials = new Credentials { ApplicationId = key };

// the actual waypoints, from start to finish.
request.Waypoints = new Waypoint[]
  // Brussels
  new Waypoint(){ Location= new Location(){ Latitude = 50.8462807, Longitude= 4.3547273}},
  // Paris
  new Waypoint(){ Location= new Location(){ Latitude = 48.8566667, Longitude= 2.3509871}},

// For the international crowd, you can also switch this to miles.
request.UserProfile = new UserProfile
  DistanceUnit = DistanceUnit.Kilometer

// some optional parameters
request.Options = new RouteOptions()
  Mode = TravelMode.Driving,
  Optimization = RouteOptimization.MinimizeTime

4. Getting the results

Last thing on the to-do list is setting up our RouteServiceClient. This will send the actual request, and get the results back in a nice RouteSummary object.

RouteServiceClient client = new RouteServiceClient();

RouteResponse response = client.CalculateRoute(request);
RouteResult result = response.Result;

The distance will be in the unit specified in the UserProfile object.
The RouteSummary object will also contain the time needed to drive in seconds.

If you like you can even get the full route path from the RouteResult object, and a lot more, but I’m not going to be able to cover that in a 5 minute post 😉

STM.NET and .NET Framework 4.0 beta 2 ( Error 1603: A fatal error occurred. )

This blog has moved, you should read this at my new place!

Recently I ran into some problems installing the latest Visual Studio 2010 beta 2. It gave me the very clear error message:

“Error 1603: A fatal error occurred.”

Well that about says it all, right…?

After a lot of googling and frustration, it seemed that my previous installation of STM.NET caused this error.

I should have remembered that  “the STM enabled version of Microsoft .NET version 4.0 and official versions of .NET
version 4.0 are mutually exclusive, and cannot be installed simultaneously on the same computer

Uninstalling STM.NET was not as easy as I thought. I assumed the almighty internet would have answers, but no dice. I spent  about a day and a half of trying almost everything : .NET Framework Cleanup tools, uninstalling anything with ‘.NET or ‘Visual’ in it’s name, registry cleaning, manually removing folders from the Windows folder  ( I got desperate ).

Finally, I found the answer, thanks to an old Microsoft Support article.

Following the next steps should help you remove the STM.NET version of .NET Framework 4.0:
Uninstall NET Framework 4 STM

  1. Go to : Start > Run > type ‘Installer’, press enter
  2. Right click on the column header and add the ‘Comments’ column
  3. Sort alphabetically and search for ‘Microsoft .NET Framework 4 Client Profile Beta 1 enabled to use Software Transactional Memory…’
  4. Right-click and uninstall!
  5. Reboot … just in case =)

This should enable you to succesfully install the ‘regular’ .NET Framework 4 Beta 2 and enjoy the new Visual Studio 2010 Beta!