Monthly Archives: May 2011

Liskovs Substitution Principle

I’m a big fan of patterns and principles. And I’m going explain all SOLID principles in different blog posts. This post is all about LSP.

LSP says that you should always be able to use a base class or interface instead of the actual implementation and still get the expected result. If you can’t, your breaking LSP.

An example:

public interface IDuck
{
   void Swim();
}
public class Duck : IDuck
{
   public void Swim()
   {
      //do something to swim
   }
}
public class ElectricDuck : IDuck
{
   public void Swim()
   {
      if (!IsTurnedOn)
        return;

      //swim logic  
   }
}

And the calling code

void MakeDuckSwim(IDuck duck)
{
    duck.Swim();
}

As you can see, there are two examples of ducks. One regular duck and one electric duck. The electric duck can only swim if it’s turned on. This breaks LSP since it must be turned on to be able to swim (the MakeDuckSwim method will not work as expected if a duck is electric and not turned on).

You can of course solve it by doing something like this:

void MakeDuckSwim(IDuck duck)
{
    if (duck is ElectricDuck)
        ((ElectricDuck)duck).TurnOn();
    duck.Swim();
}

But that would break Open/Closed principle (SOLID) and has to be implemented everywhere (and therefore still generate instable code).

The proper solution would be to automatically turn on the duck in the Swim method and by doing so make the electric duck behave exactly as defined by the IDuck interface.

The solution with turning on the duck inside the Swim method can have side effects when working with the actual implementation (ElectricDuck). But that can be solved by using a explicit interface implementation. imho it’s more likely that you get problems by NOT turning it on in Swim since it’s expected that it will swim when using the IDuck interface.

What LSP is really saying is that all classes must follow the contracts that they have been given. Just as you may not update items in your website with GET if you are following the HTTP protocol.



More natural string formatting using an extension method

If you are like me, you don’t determine if you should include parameters in string before you start writing, thus you haven’t decided that string.Format should be used until it’s too late. You then need to go back and refactor that string, which can destroy the smooth coding flow that you got going.

Lets be saved by an extension method:

public static class StringExtensions
{
	public static string FormatWith(this string instance, params object[] arguments)
	{
	    return string.Format(instance, arguments);
	}
}

Which allows you to reformat the code as:

// Simple example
Console.WriteLine("Hello '{0}'!".FormatWith("world"));

// Multiple parameters:
var str = @"Happy birthday {0}!
    {1} is a beatiful age, isn't ?".FormatWith(user.Name, user.Age);