Tom 06:56, 1 December 2009

Manipulating the DOM with Firebug

Currently I"m working more and more with jQuery and JavaScript to get behavior into my pages. This was quite painful in the beginning as I was depended a bit too much on alert"('this happens!').

But I guess this is where you get started and then find out about the excellent firebug. With the console you can then fire your JavaScript and jQuery commands to the page like so:

 

 image

 

I'm querying on of Holland's main news sites for their logo. Firebug conveniently comes up with the link to the element and when clicked it will show where it's located on the page.

This is all nice but let's change the boring logo of nu.nl to that of our own!

Easy enough, just use the following to change the picture in the page:

$('#sidemenu a img').attr('src', 'http://www.tjsolutions.nl/themes/tjs/images/headerbg.jpg')

 

 

image

 

But changing the elements in a page is just the beginning. You can just as easily add new functionality by binding a click event handler to one or more elements in the page.

 

Viewing registered events

You can also use the console to inspect what events are registered to an element on the page. All you need to do is use this syntax:

$(selector).data("events");

 

When we try that on the last input (randomly chosen) you get an overview of all the events bound (in this case only one).

 

events

 

If you the click on the object and hover over "function" you'll end up with the code itself:

 

function

 

This is a very neat trick that I wish I had stumbled upon earlier. Hope it helps.

Tom 08:56, 17 November 2009

I was pointed to the Passionate programmer by one of the blog posts at Los Techies. I'm about a third through the book and so far it has been a real joy to read!

It's full of good tips on how to alter your behavior to become something better as a programmer. I'm probably going to write some posts on what I've done with the various "act on it!", but in the meantime, go get it and start reading!

Tom 07:01, 16 November 2009

Just a quick update on my previous posting following one of the comments made by den Ben

 

just out of curiosity... why wouldn't you
dispatcher.Add<SaveDocumentRequest>(s =>
{
s.Document = document;
s.UserID = userID;
});

 

He's absolutely right. Using a Func forced me to (mis)use the params keyword as you are not allowed  to use the above syntax with the old code:

public virtual IDispatcher Add<TRequestType>(params Func<TRequestType, object>[] funcs)
    where TRequestType : Request, new()
{
    TRequestType request = new TRequestType();
    foreach (var func in funcs)
    {
        func.Invoke(request);
    }
    AddRequest(request, false);
    return this;
}

I actually had noticed the code not using the return value by the func but disregarded it as I was a bit too happy with the "elegance" of my inital solution.

But I think (and I think you'll agree) that using an Action is much cleaner here:

public virtual IDispatcher Add<TRequestType>(Action<TRequestType> action)
    where TRequestType : Request, new()
{
    TRequestType request = new TRequestType();
    action(request);
    AddRequest(request, false);
    return this;
}

 

Thanks den Ben!

Tom 08:14, 12 November 2009

One of my colleagues asked me today if I could write a utility function that would make his life more easy.

The objective was to call a stored procedure n-times for every item in a list. Of course some of the properties on every item had to be mapped to parameters in the stored procedure.

 

The desired syntax would be something like:

builder.SetStoredProcedureNameTo( " some sproc name ")
        .Execute ( customerList ,
            (s,t) => s.AddParameterWIthValue( parameterName, t.PROPERTY_NAME_1) ,
            (s,t) => s.AddParameterWIthValue( parameterName, t.PROPERTY_NAME_2) ,
             (s,t) => s.AddParameterWIthValue( parameterName, t.PROPERTY_NAME_3)
      );

 

I already have a fluent wrapper class to make our ADO.Net a bit more friendly, the interface looks like:

public interface ICustomSqlCommandBuilder
{
    ICustomSqlCommandBuilder SetStoredProcedureNameTo(string storedProcedureName);
    ICustomSqlCommandBuilder AddParameterWithValue(string parameterNameInDatabase, object value);
    ICustomSqlCommandBuilder AddExlicitOutputIntParameterToTheCommandFor(string parameterName);
    ICustomSqlCommandBuilder AddExlicitOutputDateTimeParameterToTheCommandFor(string parameterName);

    IList<TReturnType> ExecuteReaderFor<TReturnType>()
        where TReturnType : new();
}

Nothing special except for the ExecuteReaderFor<TReturnType>() but that's for another post.

 

Having the fluent interface on ICustomSqlCommandBuilder combined with the lambda magic explained in this post I came up with the following signature:

ICustomSqlCommandBuilder ExecuteScalarForThisList<T>(
    IList<T> list,
    params Action<ICustomSqlCommandBuilder, T>[] actionList);
The general idea is to apply
(s, t) => s.AddParameterWithValue("parameterName", t.PROPERTY_NAME)

to every property in the object<T> that needs to be mapped against a parameter in the stored procedure. Having the params allows us to map as many properties to parameters in the stored procedure as we like. If we then loop through all the items in the list first and apply all actions in the actionList per item, we can then call ExecuteScalar on the stored procedure.

foreach (var item in list)
{
    foreach (var action in actionList)
    {
        action.Invoke(this, item);
    }
    var result = sqlCommand.ExecuteScalar();
    sqlCommand.Parameters.Clear();
}

Now, another requirement was to wrap it in a transaction and also to have the verification of the result a bit more flexible. All in all not too complicated, just a matter of introducing another Action:

public ICustomSqlCommandBuilder ExecuteScalarForThisList<T>(
    IList<T> list, 
    Action<object> verify, 
    params Action<ICustomSqlCommandBuilder, T>[] actionList)
{
    sqlCommand.Connection.Open();
    SqlTransaction transaction = sqlCommand.Connection.BeginTransaction();
    sqlCommand.Transaction = transaction;

    try
    {
        foreach (var item in list)
        {
            foreach (var action in actionList)
            {
                action.Invoke(this, item);
            }
            var result = sqlCommand.ExecuteScalar();
            verify(result);
            sqlCommand.Parameters.Clear();
        }
        transaction.Commit();
    }
    catch (SqlException)
    {
        transaction.Rollback();
        throw;
    }
    catch (Exception)
    {
        transaction.Rollback();
        throw;
    }
    return this;
}

 

Including a bit of exceptionally brittle exception handling and calling the stored procedure on a list of Customers now resolves to:

Action<object> resultConstraint = result =>
{
    if (result != null)
    {
        if ((int)result > 1000)
        {
            throw new Exception("result should be less than 1000!");
        }
    }
};

builder
    .SetStoredProcedureNameTo("sens_sp_modifyCustomerIncome")
    .ExecuteScalarForThisList(
        customerList, 
        resultConstraint,
        (s, t) => s.AddParameterWithValue("id", t.ID),
        (s, t) => s.AddParameterWithValue("income", t.Income)
        //etc for the rest of the properties
    );
I really, really like this syntax!
Tom 05:54, 31 October 2009

At my current project we are using a dispatcher class to batch requests to our WCF layer based on the Request/Response Service Layer created by Davy Brion. Once you call the Get<TResponseType>() on the dispatcher the WCF layer starts working on the requests one by one and return them in one roundtrip.

Adding requests to the dispatcher is easy:

var saveDocumentRequest = new SaveDocumentRequest();
var getRemainingDocuments = new GetRemainingDocumentsRequest();
dispatcher.Add(saveDocumentRequest, getRemainingDocuments);

 

Where the signature of the Add method in Dispatcher is like;

public void Add(params Request[] requests)

Although this syntax is not bad, it feels like so much like code from last month: not very sexy. Wouldn't be more fun if we could spice it up a bit using generics and a bit of Func?

I'd love to get rid of instantiating a variable just for the sake of adding it to my dispatcher. After a bit of fiddling around with my unit tests I came up with the following solution.

What I want is to call the Add method in a generic way and set the parameters on my request object inline, using a Func. This is best illustrated with a test:

[Test]
public void can_assign_value_using_a_func_in_a_generic_method_call()
{
    Guid id = Guid.NewGuid();
    var dispatcher = new Dispatcher();
    
    dispatcher.Add<GetPersonsRequest>(s => s.ID = id);
    
    
    //disregard ugly cast; this is only for test purposes
    var request = (GetPersonsRequest)dispatcher.Requests.First();
    request.ID.ShouldEqual(id);
}
Where the Request and dispatcher have these signatures:
public class GetPersonsRequest:Request
{
    public Guid ID { get; set; }
}

public class Dispatcher
{
    public Dispatcher()
    {
        Requests = new List<Request>();
    }

    public void Add<TRequestType>(params Func<TRequestType, object>[] funcs)
where TRequestType : Request, new() { var request = new TRequestType(); foreach (var func in funcs) { func(request); } Requests.Add(request); } public IList<Request> Requests { get; set; } }

I can now set only property in my Request type, what if it has more properties that need to be set? Just introduce the infamous params to the method signature like so:

public void Add<TRequestType>(params Func<TRequestType, object>[] funcs) 
where TRequestType:Request, new() { var request = new TRequestType(); foreach (var func in funcs) { func(request); } Requests.Add(request); }

And again the test:

[Test]
public void can_assign_two_values_using_a_func_in_a_generic_method_call()
{
    var dispatcher = new Dispatcher();
    Guid id = Guid.NewGuid();

    dispatcher.Add<GetPersonsRequest>(s => s.ID = id, t=> t.GetAllDetails = true);

    //disregard ugly cast; this is only for test purposes
    var request = (GetPersonsRequest)dispatcher.Requests.First();
    request.ID.ShouldEqual(id);
    request.GetAllDetails.ShouldBeTrue();
}

When we change the return type of the Add method to the dispatcher itself, we can then use a fluent interface to get a very friendly syntax  for making calls:

 

//input parameters for first request
var document = new object();
var userID = Guid.NewGuid();

//input parameters for second request
var dossierID = Guid.NewGuid();

dispatcher
    .Add<SaveDocumentRequest>(s => s.Document = document, t => t.UserID = userID)
    .Add<GetZaakRequest>(s => s.DossierId = dossierID);

I really like the fact that I don't have to initialize a variable and still have access to all the properties in the request object..

Tom 06:15, 20 October 2009

I'm always trying to improve on my speed in development. Yesterday I noticed Udi Dahan using the In-proc test feature of TestDriven.Net in one of his presentations at the SDC - Netherlands, like so:

 

image

 

 

I had seen this option before but as it was hidden in some submenu and the regular test method worked just fine, there seemed no benefit in using it.

 

However.

Running your tests using In-proc makes for about 25% speed difference on average! To me, this is very noticeable but the function is hidden in some context submenu, hence still slow to use. After a bit of emailing with TestDriven.Net, it appears that you can run In-proc using the DTE runner.

To map it to a shortcut key, use the following screenshot:

 

image

Tom 02:23, 20 October 2009

I have converted quite a few to Resharper recently. I'm quite the addict myself and I can't see myself using Visual Studio productively without it anymore.

Resharper does have a learning curve however since there are just because of the sheer amount of enhancements it brings to working with VS.

 

To get you up to speed using Resharper, perform these settings in Visual studio after installing:
Within Visual studio: ALT - R - O => intellisense, completion behavior =>
Automatically show completion list in 0 milliseconds
"Check" all options except Case-sensitive prefix matching
Finally, "Only those that are at least": set this to 1

 

You can watch the following screencasts:
- James Kovacs screencasts on Resharper
- My own MVP coding demo using Resharper and Rhino mocks
- Ayende demoing Rhino mocks

(pls note that you'll need the Camtasia TSCC codec to view the last two)

 

You can use keyjedi to display the shortcuts used when someone else is looking over your shoulder. This will greatly enhance the introduction within your team. This only works on x86 systems, I have compiled the code into an x64 assembly that works on my win7 machine, let me know if you need it.

Lastly, have the developers print out the Resharper keymapping (in plastic cover preferably, in case of any coffee, tea and all that :-) )

 

If you have any further questions, please let me know.

Tom 10:31, 15 September 2009

This is the third posting in the WEWLC-series.

 

Other posts are:

I Can't Get This Class into a Test Harness

I don't have much time and I have to change it

Assumptions on the reader

 

"Getting tests in place to make changes can be a bit of a problem. If you can instantiate your class separately in a test harness, consider yourself lucky."

Instantiating a class should not be hard, if you do have issues have a look at I Can't Get This Class into a Test Harness. That should take care of most of your problems.

But instantiating is often just the first part of all the hurdles to take. The second part is writing a test for the methods inside.

 

Fortunately, in most cases, the amount of work that we have to do to write tests for methods isn't as drastic. Here are some of the problems that we can run into.

  • The method may be private

  • The method may be hard to call because it has parameters that are hard to construct

  • The method might have bad side effects (modifying a database, writing to the file system etc)

The Case of the Hidden Method

If we need to write a test for a private method we need to make it public. There are some tricks in getting visibility on the method in your tests but I don't recommend it. First of all, if there is a need for private method odds are that what you need is a another collaborator.

This is of course a rather fundamental discussion. If you do care about keeping the method invisible to callers you can make it protected. Once it is protected you can derive a test class and add a public method that will simply call the protected method in the base class.

In most cases I would recommend moving the method to a separate class and inject it into the constructor of the class that interacts with it. Once there is a need to alter the behavior of a private method it is obviously doing something important, hence, it should be under test.

 

The Case of the "Helpful" Language Feature

Michael Feather is referring to sealed classes that don't have constructor. How do you test interaction code that takes such a class as a parameter in a method? Let's have a look at an example:

public class StreamHelper
{
    const int MIN_LEN = 4;

    public IList GetStreams(HttpFileCollection files)
    {
        var list = new List<Stream>();
        foreach (string name in files)
        {
            HttpPostedFile file = files[name];
            if ((file.FileName.EndsWith(".txt") && file.ContentLength > MIN_LEN))
            {
                list.Add(file.InputStream);
            }
        }
        return list;
    }
}

According to MSDN, the HttpFileCollection provides access to and organizes files uploaded by a client. Since this class is sealed and only has an internal constructor, how can you test this method?

Turns out that HttpFileCollection derives from NameObjectCollectionBase which has a parameterless constructor which is protected. If we thus derive from NameObjectCollectionBase, implement the indexer required and change the signature of the GetStreams method a bit to take our custom class instead of the HttpFileCollection we should be able to get going.

 

Please note, this is going to be a hefty refactoring. Right, lets get down to it. First let's create a fixture for our tests:

[TestFixture]
public class HttpCollectionTests
{
    [Test]
    public void can_instantiate_a_derived_class_from_NameObjectCollectionBase()
    {
        var customHttpFileCollection = new CustomHttpFileCollection();
        var collectionBase = customHttpFileCollection as NameObjectCollectionBase;
        collectionBase.ShouldNotBeNull();
    }
}

 

This means deriving from NameObjectCollectionBase

public class CustomHttpFileCollection : NameObjectCollectionBase
{
    
}

The next test is to be able to call GetStreams() in StreamHelper. Rather than changing the existing method we are going to create a new method with the same name, but different signature so that we can call it with our new CustomerHttpFileCollection:

[Test]
public void can_use_the_custom_class()
{
    var collection = new CustomHttpFileCollection();
    new StreamHelper().GetStreams(collection);
}
public IList<Stream> GetStreams(CustomHttpFileCollection files)
{
    var list = new List<Stream>();
    foreach (string name in files)
    {
        HttpPostedFile file = files[name];
        if ((file.FileName.EndsWith(".txt") && file.ContentLength > MIN_LEN))
        {
            list.Add(file.InputStream);
        }
    }
    return list;
}

This means implementing the indexer used in GetStreams() in our custom class. Luckily Resharper knows what to do and we can use ALT-ENTER to generate the code. Next to the indexer we will also need an IList to store the files and a method to add them to the internal collection:

public class CustomHttpFileCollection : NameObjectCollectionBase
{
    public HttpPostedFile this[string name]
    {
        get { return httpPostedFiles.Where(s => s.FileName == name).FirstOrDefault(); }
    }
}

This poses a bit of an issue; we can instantiate a HttpPostedFile so how are we going to populate an internal collection? Since this one is sealed, does not have a suitable base class and has no constructors we need to be creative. We need a custom implementation of the HttpPostedFile. First we create an interface, then define the same members on the interface as are in the HttpPostedFile class. Once that is done we can change the signature of the indexer to IHttpPostedFile and add some logic to store and add the files to the collection class, like so:

public class CustomHttpFileCollection : NameObjectCollectionBase
{
    readonly IList<IHttpPostedFile> httpPostedFiles = new List<IHttpPostedFile>();

    public IHttpPostedFile this[string name]
    {
        get { return httpPostedFiles.Where(s => s.FileName == name).FirstOrDefault(); }
    }

    public void AddHttpPostedFile(IHttpPostedFile file)
    {
        httpPostedFiles.Add(file);
    }
}
public interface IHttpPostedFile
{
    int ContentLength { get; }
    string ContentType { get; }
    string FileName { get; }
    Stream InputStream { get; }
}

Change the HttpPostedFile to the new IHttpPostedFile in GetStreams():

public IList<Stream> GetStreams(CustomHttpFileCollection files)
{
    var list = new List<Stream>();
    foreach (string name in files)
    {
        IHttpPostedFile file = files[name];
        if ((file.FileName.EndsWith(".txt") && file.ContentLength > MIN_LEN))
        {
            list.Add(file.InputStream);
        }
    }
    return list;
}
 

Now that we have set up the collection, let's write a test to see if it all works

Stream GetStream()
{
    const string s = "hello world";
    var memoryStream = new MemoryStream(System.Text.Encoding.Default.GetBytes(s));
    return memoryStream;
}
[Test]
public void can_use_the_customcollection_to_test_the_StreamHelper_class()
{
    var collection = new CustomHttpFileCollection();
    var httpPostedFile = MockRepository.GenerateMock<IHttpPostedFile>();
    httpPostedFile.Stub(s => s.InputStream).Return(GetStream());
    httpPostedFile.Stub(s => s.FileName).Return("somefilename.txt");
    httpPostedFile.Stub(s => s.ContentLength).Return(5);

    collection.AddHttpPostedFile(httpPostedFile);

    IList<Stream> streams = new StreamHelper().GetStreams(collection);
    streams.Count.ShouldEqual(1);
}

When we execute this test a lot is happening. First I create a mock of the IHttpPostedFile interface so that I can stub the properties. This allows me to test the method without having an actual implementation of the interface. Not that it would have complicated things tremendously, but it's a nice technique.

I also use a convenient helper method to get me a stream. This will come in handy later when I want to verify the outcome of the GetStreams() method.

Let's execute and:

 

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

TestCase 'Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class'
failed:
  Expected: 1
  But was:  0
    at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object actual, Object expected)
    C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\HttpCollectionTests.cs(59,0): at Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class()

0 passed, 1 failed, 0 skipped, took 1.37 seconds.

 

Why is this happening? My bad, I didn't implement GetEnumerator() on the custom collection class. This is easily fixed however:

public class CustomHttpFileCollection : NameObjectCollectionBase, IEnumerable
{
    readonly IList<IHttpPostedFile> httpPostedFiles = new List<IHttpPostedFile>();

    public IHttpPostedFile this[string name]
    {
        get { return httpPostedFiles.Where(s => s.FileName == name).FirstOrDefault(); }
    }

    public new IEnumerator<string> GetEnumerator()
    {
        return httpPostedFiles.Select(s => s.FileName).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void AddHttpPostedFile(IHttpPostedFile file)
    {
        httpPostedFiles.Add(file);
    }
}

I'm using some Linq goodness to get to the filenames and iterate over that. Next up is refining our test and run it again:

[Test]
public void can_use_the_customcollection_to_test_the_StreamHelper_class()
{
    var collection = new CustomHttpFileCollection();
    var httpPostedFile = MockRepository.GenerateMock<IHttpPostedFile>();
    httpPostedFile.Stub(s => s.InputStream).Return(GetStream());
    httpPostedFile.Stub(s => s.FileName).Return("somefilename.txt");
    httpPostedFile.Stub(s => s.ContentLength).Return(5);

    collection.AddHttpPostedFile(httpPostedFile);

    IList<Stream> streams = new StreamHelper().GetStreams(collection);
    streams.Count.ShouldEqual(1);
    streams.First().Length.ShouldBeGreaterThan(0);
    new StreamReader(streams.First()).ReadLine().ShouldContain("hello world");
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.48 seconds.

 

Now note that when using the GetStreams() method one would have to transform the items in HttpPostedFileCollection to the IHttpPostedFile interface before using it.

 

 

The Case of the Undetectable Side Effect

Every so often you encounter code that just makes you mumble WTF way more than is healthy for any sane developer. In most cases things just happen everywhere. When the code is performing a query, it's also updating some other pieces, altering the file system a bit and lastly setting a whole bunch of other objects in an invalid state.

I wouldn't recommend getting the debugger up and running to see what's going on. Most of the time it consumes a lot of time and keeps the frustration really high.

What this kind of code is lacking is proper Command Query Separation (CQS). From the WEWLC book "It's a is a design principle first described by Bertrand Meyer. Simply put, it is this: A method should be a command or a query, but not both. A command is a method that can modify the state of the object but that doesn't return a value. A query is a method that returns a value but that does not modify the object."

 

You should always strive to adhere to this principle. It will make your code easier to read and more importantly, easier to skip when reading. When I encounter code that does not adhere to CQS I always split it up in several smaller methods, break out objects etc etc. Once that is done, testing immediately becomes easier on the class.

It's a matter of subclassing and overriding any behavior that is unwanted so that the method you like to test can be tested in isolation.

 

And with the Undetectable side effect covered we end the I can't get this class into a test harness chapter of WEWLC. Hope you enjoyed reading. Drop a line in the comments for feedback, or ideas.

Tom 10:14, 14 September 2009

This is the second posting in the WEWLC-series.

 

Other posts are:

I can't run this method in a test harness

I don't have much time and I have to change it

Assumptions on the reader

 

 

What to do if the system under test is a nasty legacy class that seems impossible to get under test? There are various techniques that can help you with this, let get started with "the case of the irritating parameter".

 

The case of the irritating parameter

When you have a SUT that takes complex objects into it's constructor you can easily circumvent the situation by applying Extract interface on the bothering classes.

After you have created the necessary interfaces you can utilize Rhino Mocks to generate replacement instances (mocks) of the required classes. Rhino Mocks will actually create an proxy instance for the class. Conveniently, you can then set expectations & outcomes on these mocks. So without an actual implementation you fake the system into believing it is dealing with actual classes.

Let have a look on how this works:

 

public class CreditValidator
{
    readonly IDbConnection connection;
    readonly ICreditMaster creditMaster;

    public CreditValidator(IDbConnection connection, ICreditMaster creditMaster)
    {
        this.connection = connection;
        this.creditMaster = creditMaster;
    }
}

public class CreditMaster: ICreditMaster
{
    public CreditInformation GetCreditInformation(Customer customer)
    {
        throw new NotImplementedException();
    }
}

public interface ICreditMaster
{
    CreditInformation GetCreditInformation(Customer customer);
}

First off we create an interface for the CreditMaster class. Once that is done we can start writing the test ask the Rhino MockRepository for an instance of both IDbConnection and ICreditMaster.

 

[TestFixture]
public class CreditValidatorTests
{
    [Test]
    public void can_construct_an_instance_of_the_SUT()
    {
        var connection = MockRepository.GenerateMock<IDbConnection>();
        var creditMaster = MockRepository.GenerateMock<ICreditMaster>();

        var creditValidator = new CreditValidator(connection, creditMaster);
        creditValidator.ShouldNotBeNull();
    }
}

 

This test should not throw an exception, I assert on null just to write a clear test. Run it, and surely enough the test passes.

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.35 seconds.

 

 

The Case of the Hidden Dependency

Once you get the class instantiated, we try to use it and bang! Some obscure other complex class is instantiated deep inside and causes the crash. Enter the "case of the hidden dependency". You need to remove newing the class and either move it to a public property or to the constructor. You can then either mock the constructor parameter or set it when you need through the property.

Once you start moving dependencies to the constructor of your classes it quickly starts to make sense to use a Dependency Injection Container. The one I use most frequently is Unity as it's included in EntLib and has several advantages over the other DI-containers available. For one that it's usage it's fairly simple, but even more so that is has Microsoft's backing, often a requirement at the projects I work.

 

Let's have a look at how such a configuration would look like for a hypothetical complex class Repository. First create an interface for the Repository and register it in the BootStrapper. Registration in the Unity container:

public static class BootStrapper
{
    
    public static IUnityContainer GetContainer()
    {
        var container = new UnityContainer();
        container.RegisterType<IRepository, Repository>();
        return container;
    }
}

public class Repository:IRepository
{
}

public interface IRepository
{
}

I prefer to use a static container to resolve dependencies in my applications, like so

public static class StaticContainer
{
    public static T Resolve<T>()
    {
        return BootStrapper.GetContainer().Resolve<T>();    
    }
}

Once the dependency is registered it is simply a matter of retrieving the SUT by requesting the container to construct it. In your tests you can then choose to have the container construct the dependencies or have Rhino Mocks generate the mocks after which you can set expectations on them.

 

The Case of the Construction Blob

If a constructor constructs a large number of objects internally or accesses a large number of globals, we could end up with a very large parameter list. One simple rule is to avoid the construction altogether and move the result of the creation logic into a dependency property. You could then have your DI container inject it at will or inject a mock when used in a test harness.

 

 

The case of the Irritating Global Dependency

In WEWLC, Michael Feathers writes: "Many different kinds of dependency can make it hard to create and use classes in a testing framework, but one of the hardest to deal with is global variable usage."

He's describing the hideous Singleton use in legacy code. Personally I haven't run into problems with a Singleton. Partly, because I didn't write tests at the time I was using them and on the other hand because nowadays I simply ask my DI container for a Singleton when I need it.

Still, Singletons can be a pain in the ass and you should try to avoid them. The whole idea of the singleton pattern is to make it impossible to create more than one instance of a singleton in an application. Because it is, it is particularly hard to fake. What do you do when you encounter one?

Basically you have three options, one is to replace all occurrences in the code; this can be a very tedious job, but with the aid of Resharper, one that I would recommend.

The other is to add a static method to the Singleton that will allow you to pass in a fake. First the lazy Singleton implementation (I have omitted any useful methods for  brevity):

public class PermitRepository
{
    protected PermitRepository() { }

    public static PermitRepository GetInstance()
    {
        return Nested.Instance;
    }

    public static void SetInstance(PermitRepository repository)
    {
        Nested.Instance = repository;
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        public static PermitRepository Instance
        {
            get { return instance; }
            set { instance = value; }
        }

        static PermitRepository instance = new PermitRepository();
    }
}

 

 

And to prove that getting multiple calls of the GetInstance() method will return the same object whilst using the SetInstance method will change the instance field the following test:

public class FakePermitRepository : PermitRepository
{
}
[TestFixture]
public class PermitRepositoryTests
{
    [Test]
    public void can_replace_the_PermitRepositoryInstance()
    {
        var repository = PermitRepository.GetInstance();
        int hashCode = repository.GetHashCode();

        hashCode.ShouldEqual(PermitRepository.GetInstance().GetHashCode());

        PermitRepository.SetInstance(new FakePermitRepository());
        PermitRepository.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
    }
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.35 seconds.

 

The third option is to reset the private instance field of the Singleton and set it to null. First we alter the nested class a bit so that it checks for IsNull() before returning the object:

public class PermitRepository
{
    protected PermitRepository() { }

    public static PermitRepository GetInstance()
    {
        return Nested.Instance;
    }

    public static void SetInstance(PermitRepository repository)
    {
        Nested.Instance = repository;
    }

    public static void Reset()
    {
        Nested.Instance = null;
    }

    public

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        public static PermitRepository Instance
        {
            get
            {
                if (instance.IsNull())
                {
                    instance = new PermitRepository();
                }
                return instance;
            }
            set { instance = value; }
        }

        static PermitRepository instance = new PermitRepository();
    }
}

With the test to prove that the newly created Reset() method works as expected:

[Test]
public void can_reset_the_PermitRepositoryInstance()
{
    var repository = PermitRepository.GetInstance();
    int hashCode = repository.GetHashCode();

    hashCode.ShouldEqual(PermitRepository.GetInstance().GetHashCode());

    PermitRepository.Reset();
    PermitRepository.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

2 passed, 0 failed, 0 skipped, took 0.93 seconds.

 

The Case of the Onion Parameter

In in many cases, it can be hard to create objects. Especially if they take other object that take other objects in their constructor. Every object needs to be set up in a good state, a state that makes it ready for additional work. This quite closely resembles a fat onion.

Every time when I introduce a DI container to the team I start working with I get the fat onion argument against using a DI container. Due to the steep object graph it becomes impossible to instantiate a class manually without having to instantiate many many others.

I always reply with, why bother. The DI container will take care of it. If you do find it cumbersome, apply Extract interface and inject a mock or a stub and you'll be done with it.

Feathers makes a huge point for simplicity in his WEWLC but with today's ease of use with DI containers I don't consider the argument to be valid anymore.

 

The case the aliased Parameter

If only pieces of a class that is used as a parameter causes problems, we can take another approach. If we subclass the dependency we don't have to create (yet) another interface. I personally have no issues whatsoever with many interfaces in a system as I'm a heavy Resharper user which navigating between classes and interfaces trivial.

When we've subclassed the dependency we can write any behavior we'd like to have in our fake. Obviously my preference would be to fake the class using Rhino Mocks for easy of setup and speed of writing.

 

Right, that concludes my second post on WEWLC, I can't get this class in a test harness. Hope you enjoyed it, let me know what you think.

Tom 12:55, 12 September 2009

Who hasn't been into this position? I think we all know the drill: "we'd like you to do it know and you have until xxx to fix it". How do you approach such a situation? Do you open the source and start hammering code in an unbelievable pace or do you think the changes through, think where you will be invasive and what tests need to be written?

This (long overdue) first post is regarding making those changes. I will assume you have a working understanding about this.

 

Right, let's get started. If you don't have much time and you still need to make the change there are some techniques that let you safely insert / inject code while minimizing the risk of introducing errors.

 

Sprout Method

WEWLC: "When you need to add a feature to a system and it can be formulated completely as new code, write the code in a new method. Call it from the places where the new functionality needs to be"

This is a nice trick in that it will allow you to write the new code in a test harness provided you can instantiate the system under test (SUT).

 

Suppose we a class TransactionGate that is used to post entries. These entries need to have a certain timestamp that is applied before adding the entries to the transactionBundle. 

public class TransactionGate
{
    readonly IList<Entry> transactionBundle = new List<Entry>();

    public void PostEntries(List<Entry> entries)
    {
        entries.ForEach(entry =>
        {
            entry.PostDate();
            transactionBundle.Add(entry);
        });
    }
}

 

Now the requirement is that we check whether an entry is already listed in the transactionBundle before we add it. Fair enough, we change the code to look like this:

public class TransactionGate
{
    readonly IList<Entry> transactionBundle = new List<Entry>();

    public void PostEntries(List<Entry> entries)
    {
        entries.ForEach(entry =>
        {
            entry.PostDate();
            if (!transactionBundle.Contains(entry))
            {
                transactionBundle.Add(entry);    
            }
        });
    }
}

Contrived as it may look like we are actually making the code worse. What if the next day another requirement is to alter the conditional? It would be very tempting to simply add the next bit of code as well making the code start to rot.

A better solution is to use Sprout method. In this case, filter out the entries that are already in the transactionBundle and only add those.

public class TransactionGate
{
    public TransactionGate()
    {
        TransactionBundle = new List<Entry>();
    }

    public IList<Entry> TransactionBundle { get; set; }

    public void PostEntries(IList<Entry> entries)
    {
        var newEntries = FilterEntries(entries);
        newEntries.ForEach(entry =>
        {
            entry.PostDate();
            TransactionBundle.Add(entry);
        });
    }

    IList<Entry> FilterEntries(IEnumerable<Entry> entries)
    {
        return entries
            .Where(s => !TransactionBundle.Contains(s))
            .ToList();
    }
}

It would be trivial simple to unit test the newly created method:

public class TransactionGateTests: ContextSpecification<TransactionGate>
{
    [Test]
    public void when_an_entry_is_added_that_is_already_in_the_transactionBundle_it_should_not_Be_added()
    {
        var transactionGate = new TransactionGate();
        transactionGate.PostEntries(new[] {new Entry(1), new Entry(2)});

        transactionGate.PostEntries(new[]{new Entry(1), });
        transactionGate.TransactionBundle.Count().ShouldEqual(2);
    }
}

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

1 passed, 0 failed, 0 skipped, took 1.23 seconds.

 

However, if you then create this test:

[Test]
public void when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added()
{
    var transactionGate = new TransactionGate();
    transactionGate.PostEntries(new[] { new Entry(1), new Entry(1) });
    transactionGate.TransactionBundle.Count().ShouldEqual(1);
}

if fails miserably:

------ Test started: Assembly: Koning.WEWLC.Tests.dll ------

TestCase 'Koning.WEWLC.Tests.TransactionGateTests

.when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added' failed:
  Expected: 1
  But was:  2
    at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object actual, Object expected)
    C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\TransactionGateTests.cs(25,0): at Koning.WEWLC.Tests.TransactionGateTests.

when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added()

1 passed, 1 failed, 0 skipped, took 1.24 seconds.

 

If you take a look at the initial code we wrote then it becomes obviously clear that there is a huge benefit to writing the code in a new method: the code to PostEntries does not need to change, we only need to correct the code in the GetNewEntriesFrom method.

We now have a test that fails, good! Let's add a Distinct() clause to the filtering code so that the test passes:

public class TransactionGate
{
    public TransactionGate()
    {
        TransactionBundle = new List<Entry>();
    }

    public IList<Entry> TransactionBundle { get; set; }

    public void PostEntries(IList<Entry> entries)
    {
        var newEntries = FilterEntries(entries);
        newEntries.ForEach(entry =>
        {
            entry.PostDate();
            TransactionBundle.Add(entry);
        });
    }

    IList<Entry> FilterEntries(IEnumerable<Entry> entries)
    {
        return entries
            .Distinct()
            .Where(s => !TransactionBundle.Contains(s))
            .ToList();
    }
}

Only a subtle change but one that would not have been obvious if it were not for the tests written.

 

Sprout Class

The mechanics between Sprout Class and Sprout Method are not that different. You use Sprout class if the logic you want to add really belongs in its own separate class. You can also use Sprout Class if the class to alter is difficult to get into a test harness.

 

Wrap Method

When you encounter a method that consists a lot of procedural code it is often easiest to first wrap the existing method into another method. Say we have the Following PayDispatcher class:

public class PayDispatcher
{
    public void Pay(Employee employee)
    {
        //.... a lot of code follows
    }

}

public class Employee
{
}

Suppose we are required to add logging to the Pay method following. With Resharper this extraction is made extremely easy using the key combination CTRL-R, M (Extract method). We first move the code in Pay to DispatchPayment() and then add logging.

 

You will probably end up with something like this:

public class PayDispatcher
{
    public void Pay(Employee employee)
    {
        DispatchPayment(employee);
        LogPayment(employee);
    }

    void DispatchPayment(Employee employee)
    {
        //.... a lot of code follows
    }

    void LogPayment(Employee employee)
    {
        //.... some logging code follows
    }
}

Now, the point here is to see how wrapping the method calls would increase readability and isolation of the changes. Obviously the logging could be done in several other ways.

 

Wrap Class

One of the (many) alternatives would be to completely wrap the logging into a decorator. Let's have a look.

We first have to undo the logging in the original PayDispatcher class:

public class PayDispatcher
{
    public void Pay(Employee employee)
    {
        DispatchPayment(employee);
    }

    void DispatchPayment(Employee employee)
    {
        //.... a lot of code follows
    }
}

We can then write a decorator PayDispatcher that will wrap our existing PayDispatcher and apply the required logging, like so:

public class LoggingPayDispatcher
{
    readonly PayDispatcher payDispatcher;

    public LoggingPayDispatcher(PayDispatcher payDispatcher)
    {
        this.payDispatcher = payDispatcher;
    }

    public void Pay(Employee employee)
    {
        payDispatcher.Pay(employee);
        LogPayment(employee);
    }

    void LogPayment(Employee employee)
    {
        //.... some logging code follows
    }
}
This concludes the various approaches found in WEWLC for "I don't have much time and I have to change it". Hope you liked it, let me know where to improve.
Tom 10:50, 6 September 2009

Time to start reading again. I've been picking up lot's of noise regarding Kanban lately. This let me to a post of Scott Bellware in which he describes what resources he used to study Lean.

 

This weekend I started with Lean Software Development, An Agile Toolkit by Mary & Tom Poppendieck.. The book is a very pleasant to read introduction into Lean. I will probably write follow-up post when I've completed some more of Scotts list.

 

In the meantime, I'd like to share a peek into my shelfari.