Sunday, February 1, 2009

When time is of the essence

To write tests for classes with strong, hard coded, dependencies is always hard. One very common dependency is the dependency on the DateTime.Now-property. For example we have a “HelloWorld”-class (I’ve never written a Hello World-example actually so I just had to) that should greet us differently depending on the time of day.

   1: public class HelloWorld
   2: {
   3:     public string Greet()
   4:     {
   5:         var hour = DateTime.Now.Hour; 
   6:  
   7:         if (hour > 6 && hour < 12)
   8:         {
   9:             return "Good morning world!";
  10:         } 
  11:  
  12:         if (hour > 20 || hour <= 6)
  13:         {
  14:             return "Good night world!";
  15:         } 
  16:  
  17:         return "Hello world!";
  18:     }
  19: }

This code is very hard to test because we would have to either run the test on different times of the day to see that it returns the correct result or we would have to make the test set the system time in order to test the output. What we would like to do is to stub, mock or in some other way fake out the DateTime.Now property but we can’t since it’s a static. To break this dependency we’ll have to add some layer of indirection between the code and the static property. This is where dependency injection comes into play. As the code is right now, there’s no way for someone looking from the outside to see that this class has a dependency on the DateTime.Now-property. Using dependency injection and more specifically constructor injection makes this very clear.

First of all, let’s create our “layer of indirection”, the SystemTime-delegate which is a simple delegate type that returns the current time of the system.:

   1: public delegate DateTime SystemTime();

Now we make this dependency explicit by having our class take an instance of a SytemTime-delegate in it’s constructor and also we’ll use this delegate to access the system time rather than the DateTime.Now-property:

   1: public class HelloWorld
   2: {
   3:     SystemTime systemTime; 
   4:  
   5:     public HelloWorld(SystemTime systemTime)
   6:     {
   7:         this.systemTime = systemTime;    
   8:     } 
   9:  
  10:     public string Greet()
  11:     {
  12:         var hour = systemTime().Hour; 
  13:  
  14:         if (hour > 6 && hour < 12)
  15:         {
  16:             return "Good morning world!";
  17:         } 
  18:  
  19:         if (hour > 20 || hour <= 6)
  20:         {
  21:             return "Good night world!";
  22:         } 
  23:  
  24:         return "Hello world!";
  25:     }
  26: }
  27:  

Now it’s very easy to create tests that verify the output at different times by passing SystemTime-delegates that provide different times of the day:

   1: [TestFixture]
   2: public class HelloWorldTests
   3: {
   4:     [Test]
   5:     public void Greet_should_return_good_morning_in_the_morning()
   6:     {
   7:         HelloWorld greeter = new HelloWorld(() => DateTime.Parse("2000-01-01 07:00", CultureInfo.InvariantCulture));
   8:         
   9:         var greetingPhrase = greeter.Greet();
  10:  
  11:         Assert.AreEqual("Good morning world!", greetingPhrase);
  12:     }
  13:  
  14:     [Test]
  15:     public void Greet_should_return_good_night_in_the_evening()
  16:     {
  17:         HelloWorld greeter = new HelloWorld(() => DateTime.Parse("2000-01-01 21:00", CultureInfo.InvariantCulture));
  18:  
  19:         var greetingPhrase = greeter.Greet();
  20:  
  21:         Assert.AreEqual("Good night world!", greetingPhrase);
  22:     }
  23: }

And of course for production code you’d just pass in a delegate that access the DateTime.Now-property, preferably using an IoC-container, but it could certainly be done manually.

   1: var greeter = new HelloWorld(() => DateTime.Now);

Sunday, January 25, 2009

ReaderWriterLockSlim

I had totally missed that there was a new class added to the System.Threading namespace in version 3.5 of the .Net framework, namely the System.Threading.ReaderWriterLockSlim class. This is more or less a total replacement for the ReaderWriterLock-class and the wacky name is because they had to leave the old class in, mostly for compatibility reasons. Joe Duffy has a nice post about it here.

Technorati-taggar: ,,,

Saturday, January 24, 2009

SOLID

Robert “Uncle Bob” C. Martin coined the acronym SOLID a couple of years ago and though I’m fairly familiar with all of the principles I’d like to really make sure I’ve understood them all so I think I’m going to write a little series, one post for each principle. As the first post here’s a list of the principles.

 

  • Single responsibility principle
  • Open closed principle
  • Liskov substitution principle (way cool name)
  • Interface segregation principle
  • Dependency inversion principle

You sound so smart when saying things that ends in –principle.

Check out Scott Hanselman’s interview with uncle Bob on Hanselminutes.

Monday, January 5, 2009

HtmlTextWriter fluent interface

EDIT: The code demonstrated in the article is part of the Legend open source project you can find at http://legend.codeplex.com/.

If you've ever created a web control - and God knows I've created a few of them - you've most definitely come in contact with the HtmlTextWriter. If you have you've probably sworn a couple of times over how clunky it is. The amount of code you have to write to create quite simple pieces of html is just insane.

For example, take this very basic html tag:

<div id="id" name="name" class="class">Lorem ipsum.</div>

To create the same output with the HtmlTextWriter you'd have to write the following:

public void Render(HtmlTextWriter writer)
{
    writer.AddAttribute(HtmlTextWriterAttribute.Id, "id");
    writer.AddAttribute(HtmlTextWriterAttribute.Name, "name");
    writer.AddAttribute(HtmlTextWriterAttribute.Class, "class");
    writer.RenderBeginTag(HtmlTextWriterTag.Div);
    writer.Write("Lorem ipsum.");
    writer.RenderEndTag();
}

Now, you might think that that's a lot of code to accomplish very little, but that's not what's worst, it's utterly unmaintainable. Let's say we have more than one tag to render, and possibly child-tags of these tags, it soon becomes very hard to tell where a tag starts and ends and the structure of the output is hidden behind this procedural code. Well, what can we do to solve this? Extension methods to the rescue, what if we could write the above code in the following manner:

public void Render(HtmlTextWriter writer)
{
    writer
        .Tag(HtmlTextWriterTag.Div, e => e.Id("id").Name("name").Class("class"))
            .Text("Lorem ipsum.")
        .EndTag();
}

The "Tag", "Text" and "EndTag" methods are all extension methods for the HtmlTextWriter-class, this means that they're nothing more than static methods and they do not present any runtime overhead (memory wise at least, they do create an extra call on the stack).

Attributes

One of the most counter intuitive features of the HtmlTextWriter is that you specify attributes of a tag before you create the tag, to remedy that I created an overload of the Tag-extension where the second parameter is a delegate that takes an argument of the type HtmlAttributeManager. An HtmlAttributeManager is just a simple class that wraps an HtmlTextWriter to provide an interface for adding attributes fluently:

public static void Example(HtmlTextWriter writer)
{ 
    // All attributes can be set via the indexer that takes
    // the type of attribute to set and the value for it:
    writer.Tag(HtmlTextWriterTag.Div, e => e[HtmlTextWriterAttribute.Id, "id"]);

    // The indexer returns the HtmlAttributeManager-instance so calls
    // can be chained like this:
    writer.Tag(HtmlTextWriterTag.Div, e => e[HtmlTextWriterAttribute.Id, "id"][HtmlTextWriterAttribute.Name, "name"]);

    // Some common attributes can be set through named methods:
    writer.Tag(HtmlTextWriterTag.Div, e => e.Id("id").Name("name"));

    // Note that those calls can be chained to, you can even mix
    // calls to the indexer and the named methods like this:
    writer.Tag(HtmlTextWriterTag.Div, e => e.Id("id")[HtmlTextWriterAttribute.Title, "Lorem ipsum."].Class("class"));
}

Let's have a look at how the syntax looks for a little longer html-snippet, here I render the same html, first by a static string, and the via the fluent interface:

public void RenderUsingString(HtmlTextWriter writer)
{
    var html = @"
    <div class=""someClass someOtherClass"">
        <h1>Lorem</h1>
        <select id=""fooSelect"" name=""fooSelect"" class=""selectClass"">
            <option value=""1"" title=""Selects the number 1."">1</option>
            <option value=""2"" title=""Selects the number 2."">2</option>
            <option value=""3"" title=""Selects the number 3."">3</option>
        </select>
    </div>
    ";

    writer.Write(html);
}

public void RenderusingExtensionMethods(HtmlTextWriter writer)
{
    writer
        .Tag(HtmlTextWriterTag.Div, a => a.Class("someClass", "someOtherClass"))
            .Tag(HtmlTextWriterTag.H1).Text("Lorem").EndTag()
            .Tag(HtmlTextWriterTag.Select, t => t.Id("fooSelect").Name("fooSelect").Class("selectClass"))
                .Tag(HtmlTextWriterTag.Option, t => t[HtmlTextWriterAttribute.Value, "1"][HtmlTextWriterAttribute.Title, "Selects the number 1."])
                    .Text("1")
                .EndTag(HtmlTextWriterTag.Option)
                .Tag(HtmlTextWriterTag.Option, t => t[HtmlTextWriterAttribute.Value, "2"][HtmlTextWriterAttribute.Title, "Selects the number 2."])
                    .Text("2")
                .EndTag(HtmlTextWriterTag.Option)
                .Tag(HtmlTextWriterTag.Option, t => t[HtmlTextWriterAttribute.Value, "3"][HtmlTextWriterAttribute.Title, "Selects the number 3."])
                    .Text("3")
                .EndTag(HtmlTextWriterTag.Option)
            .EndTag(HtmlTextWriterTag.Select)
        .EndTag(HtmlTextWriterTag.Div);
}

Now that's a lot more readable than the same code would've been using the normal way of rendering with the HtmlTextWriter, actually, let's have a look at how that would look.

public void RenderUsingHtmlTextWriterStandardMethods(HtmlTextWriter writer)
{
   writer.AddAttribute(HtmlTextWriterAttribute.Class, "someClass someOtherClass");
   writer.RenderBeginTag(HtmlTextWriterTag.Div);

   writer.RenderBeginTag(HtmlTextWriterTag.H1);
   writer.Write("Lorem");
   writer.RenderEndTag();

   writer.AddAttribute(HtmlTextWriterAttribute.Id, "fooSelect");
   writer.AddAttribute(HtmlTextWriterAttribute.Name, "fooSelect");
   writer.AddAttribute(HtmlTextWriterAttribute.Class, "selectClass");
   writer.RenderBeginTag(HtmlTextWriterTag.Select);

   writer.AddAttribute(HtmlTextWriterAttribute.Value, "1");
   writer.AddAttribute(HtmlTextWriterAttribute.Title, "Selects the number 1.");
   writer.RenderBeginTag(HtmlTextWriterTag.Option);
   writer.Write("1");
   writer.RenderEndTag();

   writer.AddAttribute(HtmlTextWriterAttribute.Value, "2");
   writer.AddAttribute(HtmlTextWriterAttribute.Title, "Selects the number 2.");
   writer.RenderBeginTag(HtmlTextWriterTag.Option);
   writer.Write("2");
   writer.RenderEndTag();

   writer.AddAttribute(HtmlTextWriterAttribute.Value, "3");
   writer.AddAttribute(HtmlTextWriterAttribute.Title, "Selects the number 3.");
   writer.RenderBeginTag(HtmlTextWriterTag.Option);
   writer.Write("3");
   writer.RenderEndTag();

   writer.RenderEndTag();

   writer.RenderEndTag();
}

The code produced when using the fluent interface is a lot closer to the end result, the html code, so it's a lot easier to decipher (read), which means that it's  lot more maintainable.

I've also added some functionality for simple data binding and repeating, more about that next time.

Thursday, November 6, 2008

The art of making the simple complex

I was going through our use of session variables in Asp.net today at work and found code very similar to the following on multiple places:

If Session("foo") Is Nothing Then
    Session.Add("foo", value)
Else
    Session.Remove("foo")
    Session.Add("foo", value)
End If

First off, if you thought you really had to use the "Add" method to set the value why not do the following:

If Not Session("foo") Is Nothing Then
    Session.Remove("foo")
End If 

Session.Add("foo", value)

Now, ofcourse, there's really no need to check if the value exists in the session before removing it since the "Remove" method throws no exception, so we'll just write:

Session.Remove("foo")
Session.Add("foo", value)

But ofcourse, any sensible developer would instead write:

Session("foo") = value

Saturday, October 18, 2008

Implementing interfaces in VB.Net

In this post I'll talk about VB's explicit interface implementation and how to best exploit the power this brings. I guess that it's a well known fact that interface implementation in VB is explicit but what does that mean really? It simply means that to implement an interface in a class the developer has to explicitly declare what members of the class implements the members of the interface. C# also has the ability to explicitly implement interfaces but it supports implicit interface implementation too which lets you implement an interface by declaring members with the same names and signatures as those of the interface. To implement the IDisposable interface implicitly we'd write the following:

public class Foo : IDisposable
{
    public void Dispose()
    {
        // Implementation here...
    }
}

The developer never tells the compiler that the method named "Dispose" implements the method "Dispose" of the IDisposable interface, the compiler figures this out by comparing the name and the signature of the method. To explicitly implement an interface in C# we'd write the following instead:

public class Foo : IDisposable
{
    void IDisposable.Dispose()
    {
        // Implementation here...
    }
}

In this implementation we explicitly say that the "Dispose" method implements the "Dispose" method of the interface IDisposable, note that there is no scope declared for this method, this is because it's only accessible through the interface. If you held an instance of the class "Foo" you would not be able to invoke the Dispose method without casting the instance to IDisposable.

Foo foo = new Foo();

foo.Dispose(); // will not compile
(foo as IDisposable).Dispose(); // will compile

As seen here this means that a method that implements an interface method must have the same name as the interface method and be public OR have no name at all and be private (explicit implementation). In VB on the other hand where implementation is always explicit we have a lot more freedom regarding naming and scope. For example a method implementing an interface method can have any scope (Private, Protected, Friend or Public) and also any name. Oh, well, any valid name that is.

Public Class Foo
    Implements IDisposable

    Public Sub ThisMethodIsNotNamedDispose() Implements IDisposable.Dispose
        ' Implementation here...
    End Sub

End Class

Now we have a public method called something completely different than "Dispose" but still implementing the "Dispose" method, if you were to cast an instance of the Foo class to the IDisposable interface and call the "Dispose" method on it the method "ThisMethodIsNotNamedDispose" would be invoked. As I said earlier an implementing method can have any scope, the method "ThisMethodIsNotNamedDispose" could just as well have been made private for example and we would end up with a situation very similar to the C# way of explicitly implementing interfaces. One very big difference though is that from within the class Foo you'd be able to call the method "ThisMethodIsNotNamedDispose" even though it's private, in C# however you can never call an explicit member implementation without casting to the interface, not even from within the implementing class itself.

Another cool thing about VB's explicit interface implementation is that a single method or property can implement methods or properties from multiple interfaces at the same time.

Public Class Foo
    Implements ICollection, ICountable

    '...

    Public ReadOnly Property Count() As Integer Implements ICollection.Count, ICountable.Count
        Get
            Return theCount
        End Get
    End Property

    '...

End Class

Public Interface ICountable
    ReadOnly Property Count() As Integer
End Interface

Interface implementation is one of the very few areas where I think VB outshines C# (XML-literals being the other area).

I think that hiding the methods of the interface in the public interface of the class (by explicitly implement the interface in C# and setting a non public scope in VB) is something that should be sparsely used. I use it only when a method makes no sense when the concrete type is known. For example if you create a LinkedList that implements the ICollection(T) interface there is really no need to ever call the "IsReadOnly" property when you know that you're holding a LinkedList that is never read only, this interface property should be hidden from the public interface of the class.

I've used the IDisposable interface as an example here but I would strongly advice against ever hiding the "Dispose" method of this interface in production code.

Field prefixes

The debate on whether to prefix private variables with a leading "_" or "m_" has engaged a lot of people lately since the public release of Style Cop which which enforces the "m_"-prefix (at least that's what I've been told, I haven't had a chance to try the application myself yet).

I think that prefixes are always bad, whether it's an "I" for interface, "C" for class or "m_" for member. I do appreciate the historic reasons for them but there is really no valid reason anymore, we have the "this" and "Me" keywords in C# and VB to differentiate between member variables and local variables or parameters. The only valid reason as I see it is to differentiate between a field and the property that expose that field.

public class Foo
{
    protected string _bar;

    public string Bar
    {
        get { return _bar; }
        set { _bar = value; }
    }
}

You might say that you could just use camelCasing for the field and PascalCasing for the property, but suppose that the class was to be inherited by VB.Net, "bar" would now be ambigous because VB is case insensitive thus the prefix has some validity. However since the introduction of automatic properties I see no reason for the prefix anymore. The only reason would have to do with performance (you could access the field direclty from inside the class rather than through the property) and I'd say that in most cases that's neglectible and I'd go with the increased maintainability the automatic properties gives you. Premature optimization is the root of all evil. Also in the example, if the backing field was just declared as private (as it should) there would be no issue.