Tuesday, February 07, 2012

Example of Builder Design Pattern

I happened to come across an interesting idea from a Java blogger regards the Builder design pattern. For those of you who are not familiar with this pattern, check out the Wikipedia explanation. Check out this code:

    public class Address
    {
        public string Protocol { get; set; }
        public string Description { get; set; }
        public int Port { get; set; }
        public string Path { get; set; }
        public string Url { get; set; }

        private Address(AddressBuilder addressBuilder)
        {
            this.Protocol = addressBuilder._protocol;
            this.Url = addressBuilder._url;
            this.Port = addressBuilder._port;
            this.Path = addressBuilder._path;
            this.Description = addressBuilder._description;
        }

        public interface IBuild
        {
            Address Build();
            IBuild Description(string description);
            IBuild Path(string path);
            IBuild Protocol(string protocol);
        }

        public interface IPort
        {
            IBuild Port(int port);
        }

        public interface IUrl
        {
            IPort Url(string url);
        }

        public static IUrl Builder()
        {
            return new AddressBuilder();
        }

        public class AddressBuilder : IUrl, IBuild, IPort
        {
            public string _description;
            public string _path;
            public int _port;
            public string _protocol;
            public string _url;

            public Address Build()
            {
                return new Address(this);
            }

            public IBuild Description(string description)
            {
                this._description = description;
                return this;
            }

            public IBuild Path(string path)
            {
                this._path = path;
                return this;
            }

            public IBuild Port(int port)
            {
                this._port = port;
                return this;
            }

            public IBuild Protocol(string protocol)
            {
                this._protocol = protocol;
                return this;
            }

            public IPort Url(string url)
            {
                this._url = url;
                return this;
            }
        }
    }

Now there’s a lot going on here, but lets see what the above code allows us to do:

var address = Address.Builder()
    .Url("ddd")
    .Port(23)
    .Build();

We can build an Address instance using the Builder pattern, which has this nice fluent API to it. The key idea is that, since port and url are mandatory fields, we have designed the builder in such a way that those fields must be given a value before the “Build()” method can be called. If you look at the code you’ll see that this is achieved by having a nested “Builder” class that implements private interfaces associated with the Address object. The method “Address.Builder()” returns a new Builder instance via the IUrl interface. That interface has a “Port” method which must be called. The Port method returns an IBuild interface which has the “Build()” method which will actually create the Address instance.

Have a play around with this code, I think it’s a very nice way to create objects whilst making it clear which properties are mandatory.

Monday, November 21, 2011

The Agile Testing & BDD eXchange 2011

Check out these videos taken from the recent The Agile Testing & BDD eXchange. You'll find talks on topics such as:

- BDD
- Living Documentation
- Testing

I know what I'll be watching tonight :) (Coffee? (Check), Biscuits? (Check), Slippers? (Check))

Sunday, November 20, 2011

KnockoutJS 1.3 Almost Here

For those of you who are fans of Steve Sanderson’s excellent MVVM (Model View View Model) framework KnockoutJS, you'll be pleased to hear that the release candidate for version 1.3 is now available. There are a number of improvements including better syntax for defining event handling (a popular fix for many people who felt that the current method of event binding was a bit messy).

Check out this blog article by Steve, which talks about the upcoming changes.

Saturday, November 19, 2011

Using MSpec.Fakes–Part 2

Next example I’d like to show is how to force a method to return a specific value:

public class example_when_told_to : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () =>
        {
            sut = An<IHelper>();
            sut.WhenToldTo(s => s.OK(Arg<int>.Is.Anything)).Return(4567);
        };

    private Because of = () => result = sut.OK(1);

    private It should_be_4567 = () => result.ShouldEqual(4567);
}

Here I use ‘WhenToldTo()’ in order to control the return value of ‘OK()’. I could also do this:

public class example_when_told_to : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () =>
        {
            sut = An<IHelper>();
            sut.WhenToldTo(s => s.OK(23)).Return(4567);
        };

    private Because of = () => result = sut.OK(23);

    private It should_be_4567 = () => result.ShouldEqual(4567);
}

So when ‘OK()’ is called with a specific argument, in this case 23, I want to return the value 4567. OK, so let’s have a look at using the ‘WithSubject’ parent class. First, we need the code for the salary calculator which Helper is using:

public interface ISalaryCalculator
{
    double CalculateSalary(double baseSalary, double bonus);

    int GetValue();
}

public class SalaryCalculator : ISalaryCalculator
{
    public double CalculateSalary(double baseSalary, double bonus)
    {
        return baseSalary + bonus;
    }

    public int GetValue()
    {
        return 34;
    }
}

Now here is the example test class we’ll be referencing:

public class example_using_WithSubject_1 : WithSubject<Helper>
{
    private static int result;

    private Establish context = () => The<ISalaryCalculator>().WhenToldTo(x => x.GetValue()).Return(1);

    private Because of = () => result = Subject.OK(1);

    private It should_be_1 = () => result.ShouldEqual(1);
}

We’re using WithSubject and passing it the type of Helper. What this give us is a .Subject property that we can use to access the SUT (i.e. the instance of Helper). The other cool thing is that since Helper requires an implementation of ISalaryCalculator in it’s constructor, an instance of ISalaryCalculator will be created for us. Not only that, but we can control the behaviour of the ISalaryCalculator instance via the ‘The<>’ method.

In the above example I’m stating that when ISalaryCalculator.GetValue() is called, it should return 1. We can also verify calls against the ISalaryCalculator like this:

public class example_using_WithSubject_2 : WithSubject<Helper>
{
    private static int result;

    private Because of = () => result = Subject.OK(1);

    private It should_be_1 = () => The<ISalaryCalculator>().WasToldTo(x => x.GetValue());
}

That’s all for now. I might write a bit more about using Stubs in your MSpec.Fakes tests for part 3.

Thursday, November 17, 2011

Using MSpec.Fakes–Part 1

I decided to try out MSpec.Fakes, just to see how it works and to write a very quick guide on how to use it. First, in Visual Studio 2010, I added a reference to MSpec.Fakes via NuGet:

Nuget

I chose the RhinoMocks flavour mainly as I had dabbled with both it and Moq in the past and felt that RhinoMock annoyed me less Smile (Note: I’m a TypeMock user by heart, but I often have to use an open source mocking framework, in order that all devs on the team can run the tests. TypeMock does have it’s critics, but it’s by far my choice of isolation framework, but that’s for another post.)

OK, once installed, I created a couple of nonsense classes and interfaces in order to help me get up and running:

public interface IHelper
{
    int OK(int number);
}

public class Helper : IHelper
{
    private readonly ISalaryCalculator salaryCalculator;

    public Helper(ISalaryCalculator salaryCalculator)
    {
        this.salaryCalculator = salaryCalculator;
    }

    public int OK(int number)
    {
        return this.salaryCalculator.GetValue();
    }
}

Here’s my MSpec test, I’ll explain what’s going on next:

public class when_given_a_number : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () => { sut = An<IHelper>(); };

    private Because of = () => result = sut.OK(1);

    private It should_have_been_passed_a_number = () => sut.WasToldTo(s => s.OK(Arg<int>.Is.Anything));
}

Notice that the test class inherits WithFakes, this parent class has the support for the faking implementation. The cool thing is that, regardless of the underlying mocking framework you choose to use (Moq, RhinoMock) the MSpec.Fakes API is the same. I really like this approach. Next thing to look at is how we create an instance of the Subject Under Test (SUT)

private Establish context = () => { sut = An<IHelper>(); };

The An<>(); method takes care of calling the RhinoMock equivalent of

var mockRepository = new MockRepository();
var helperMock = mockRepository.CreateMock<IHelper>();

After calling the .OK() method, the assertion for this test is that sut.OK() was called with any number:

private It should_be_1 = () => sut.WasToldTo(s => s.OK(Arg<int>.Is.Anything));

Here we see the .WasToldTo() method which takes care of verifying that .OK() was indeed called with any number. Simples.

In my next post I will show some more examples.

Friday, November 11, 2011

Using Jing To Record Videos

For the past few weeks I have been using Jing, a screencast tool available from TechSmith. Jing comes in two flavours: Free and Pro. I use the free edition. If you purchase the Pro version you do get the ability to save videos in MPEG-4 format (the free edition only allows you to create SWF files).

I learnt about Jing after reading this blog article on the Telerik site. They use Jing to record the progress of features completed by developers. This provides instant feedback to the team on how a feature has been implemented. I really like that idea and started to use it at work, though I’ve been recording videos to help document how I resolved some customer issues which are reported to us. I’ve also recorded videos which show how to configure IIS for client who wanted 301 redirects for certain url’s on their site. The videos have proved really useful, no to mention the amount of time saved when compared to writing out documentation by hand!

Tuesday, August 16, 2011

Getting Ready For Windows 8

It doesn’t feel all that long ago when Windows 7 was released. Now, Microsoft are getting ready to introduce the world to Windows 8. Check out the Building Windows 8 blog where MS will be posting allsorts about the next OS. Back in 2008 MS began writing about Windows 7 using the same blog, which proved very popular, so they have decided to repeat this idea. Considering the lack of detail MS have thus far released about Windows 8, I’m sure many people will regularly keeping an eye on the new blog!