Posted by: ronniebarker | December 10, 2008

MethodChaining

I was recently part of a small talk with a selection of the dev team at Elateral about fluent interfaces. I was introducing the concept of method chaining with an example based upon Martin Fowler’s post that I had worked on when discussing some best practices with some of the guys at DisplayLink.

I had a small slide deck that really served only as a prompter for me to introduce the concepts and worked through the example. I promised to upload them all somewhere for general access so here it is.

All the files should be accessible here – they are as follows (individual links):

Slide deck
C# “ComputerBuilder” example
C++ “ComputerBuilder” example

I have already started using the C# example to further investigation into nBehave. I now have an acceptance test that reads something like:

story
        .AsA( Computer )
        .IWant( "to be configured" )
        .SoThat( "I work" );

story
        .WithScenario( "Martin Fowler's example" )
        .Given( "a new computer builder", () => chain = Computer.New )

        .When( "I give it two cores", () => chain = chain.WithCores( 2 ) )
        .And( "set it to be an i386", () => chain = chain.OfType( Processor.i486 ) )
        .And( "add a 150GB disk", () => chain = chain.WithDisk.OfSize( 150 ) )
        .And( "add a 7200rpm 75GB SATA disk ", () => chain = chain.WithDisk.IsSata.OfSpeed( 7200 ).OfSize( 75 ) )

        .Then( "I expect to get a Computer out", () => ( computer = chain ).ShouldBeInstanceOf<Computer>() )
        .And( "I expect to have a computer with $expectedCores cores", 2, expectedCores => computer.NumberOfCores.ShouldEqual( expectedCores ) )
        .And( "an $expectedProcessor processor", Processor.i486, expectedProcessor => computer.Processor.ShouldEqual( expectedProcessor ) )
        .And( "$expectedDiskCount disks", 2, expectedDisks => computer.Disks.Count.ShouldEqual( expectedDisks ) )
        .And( "the first disk should have a size of $expectedSize GB", 150, expectedSize => computer.Disks[ 0 ].Size.ShouldEqual( expectedSize ) )
        .And( "the second disk should have a size of $expectedSize GB", 75, expectedSize => computer.Disks[ 1 ].Size.ShouldEqual( expectedSize ) )
        .And( "the second disk should be SATA", () => computer.Disks[ 1 ].Sata.ShouldBeTrue() )
        .And( "the second disk should have a speed of $expectedSpeed rpm", 7200, expectedSpeed => computer.Disks[ 1 ].Speed.ShouldEqual( 7200 ) )
        ;

I am also using this example as part of a continuous integration experiment and hope to refactor to use interfaces and a single builder – more on these things later…


Responses

  1. excellent work
    i recognise some of those ideas :)
    me


Leave a response

Your response:

Categories