Interface first development and Mocking [Overview]

30 Second Overview

Although this technique really falls within the ‘Emergent Design Umbrella’ it would be remiss of me to not to write a quick overview.

This technique introduces two visualizing concepts to the reader:

  • Coding shallow and wide
  • Implementing deep

Ok so what does all that mean , well in simple terms your aim is to code in multiple passes the first pass you implement the behaviour to satisfy your BDD test by hammering out interfaces and you mock everything do not even allow your mind to wonder to the how do i implement X instead just trust that it will become clear as you proceed.

So in the first pass everything or almost everything is a mock and you will be passing values into one mock and pulling them out of another when you stand back and look at that first pass your first reaction will be that’s pointless, mine certainly was the first time i did.

But if you have now coded shallow.

So next start pushing down towards your deep end point perhaps a mocked repository or some such. So next you might make the Adapter concrete and start to implement a service call perhaps via a channel factory. This will of course lead you to implement the service and because we are best practise team you will be injecting into it via its constructor (DI/IOC) its repository which is still mocked.

So you will be driven in the setup code for your test to hammer out the host and perhaps a Unity (or other DI) service behaviour/host/ binding then you will rerun your test ad you will find that now you have coded deep and implemented the behaviour you prototyped in the first pass. So you move on till you get to the your test end point which might be a in memory database or a mocked repository or something else that suits your domain pattern.

The golden rule with this is ‘ Implement only when driven there, delay implementation of an object as long as practical and sensible’.

Emergent Design [Overview]

30 Second Overview.

This technique says that ‘As our requirements are implemented so our underlying design will emerge’ although it is likely that we will have made some over arching decisions such as the client application will be Silverlight we will use RIA services and so on.

In simple terms the design decisions are delayed until we are driven to make them by following our Tests and the artefacts produced by those tests. So there is no upfront design phase and no need for a architect or technical lead as all members of the team are equally empowered and responsible for architectural decisions as they get to the point a decision can no longer be delayed.

Emergent Design says also that all developers in the team are equally empowered and there is no need for a tech lead or over arching solution architect / design authority although you may still need a gate keeper for the domain / domain architect to enforce company wide design options and integration between systems.

Using this principal, communication is imperative across the team , headphones should not be warn in this type of environment information saturation via Osmosis is beneficial as is courage to speak if you don’t agree with something you over hear.

It is also a classic aspect of this type of team that documentation will live in card task lists and although at a seconds notice any team member will be able to draw for you on a white board the solution architecture no architecture diagrams will be produced and generally Visio is a dirty word as each member would expect his colleagues to be able to run a white board session to explain the current architecture therefore making diagrams a outdated slow moving asset that has no place in a emergent environment.

Some of the advantages

  • Fast iterative cycles
  • Flexibility within the architecture to change as the requirement dictates ( flock of swallows principal )
  • Spread of architecture knowledge across the team
  • High quality development , is achieved by architectural chooses under continual review by all developers
  • Highly empowered and motivated team
  • Distributed code and architecture ownership
  • Encourages small checkins and atomic coding practises
  • Highlights weaknesses in the team quickly and encourages individual and team level skill patching
  • Iteration 0 /1 is a productive iteration rather than spending it debating architecture
  • With this style of team everything is immediate you see it , you deal with it very little technical debt is built up as the team will feel uncomfortable with passing by a architectural issue and not solving it immediately, this could probably belong in both challenges and advantages though i see it as the latter speaking from a personal stand point.
  • This method tends to lead to a lot of code reuse and due tot he high rate of refactor that is performed with this method the code tends to be of a very high quality with very little fat and subsequent lower maintenance foot print.
  • Because the code is under continual review by the whole team plus the reliance on B/TDD techniques the bug count at point of release is normally very very low.

Some of the challenges

  • Recruitment becomes very difficult as all the people on the team must pass a minimum bar there is no room for juniors on teams practising this principal, or passengers. ( Principal the team is in this case as strong as its weakest member and as fast as its slowest pair )
  • High code churn as the architectural changes are implemented on the fly across the whole solution not just the focus of that particular card , a architectural refactoring must be cross cutting across preceding code as well as the current card scope.
  • Team must communicate verbally , its imperative that the person proposing an architectural change communicates that change to the rest of the team and they respond in a speedy and honest fashion – fast white board sessions are ideal for this ( hint: time box), there is no place to hide in this sort of team.
  • Velocity can become uneven as people make large refactors, reducing there perceived productivity.
  • This technique does not work well in distributed teams, with out implementing a lot of overhead.
  • It is imperative that there is a understanding of you touched it you own it , in other words just because you didn’t write it , doesn’t mean you can see something you disagree with and pass it by and mentally think ‘ oh well its not my code’.
  • If used with teams that lack maturity or teams that have an element within them that has not brought into this technique , this technique can cause a lot of animosity.
  • It is imperative that this technique is practised with full test coverage , a solid CI (Continuous Integration) it is generally a rule with teams that practise this approach that the code base is constantly deliverable, demoable and a candidate for shipping should it be required, any high risk development is done in a branch and then integrated and generally is spik’ed out first.
  • This technique works best in self organising teams and works badly in command and control style structures.

BDD [Overview]

30 Second Overview.

One of the main disciplines the teams i work with is Behaviour Driven Development this approach to software design was introduced to the community by Dan North a number of years ago and although it has not gained the following its sister discipline of TDD (Test Driven Development) has gained, those that practise BDD tend to produce a far more accurate representation of the Business Analysts vision and thus the customers dream.

Within a BDD Test / Spec we aim to use common English language sentence to describe the functionality that we need to be produced our scope is a business stripe though the technical layers rather than a method or object as in TDD.

Brief Presentation on some of the BDD frameworks in common use: https://www.box.net/shared/2tfmm2ubgo

Some of the advantages

  • Requirements are the driving force behind the tests , which in turn drives the code
  • The technique trims away code waste
  • The technique creates a pit of success for the developer
  • The technique encourages other good practises such as contract first development and emergent design principals.
  • Helps developers understand what ‘Done’ really is for the story

Some of the challenges

  • The technique requires a lot of discipline across the team
  • The technique takes away some of the freedom from developers
  • The technique doesn’t work in environments where P & P , SOLID and best practises are not followed.
  • The technique required a ‘BA’ role to be performed within the team
  • The BA must be very explicit in there requirements and child acceptance criteria, also it is helpful if they supply wireframes and such like to augment the requirement statements

Making the Magic happen.

Introduction

 

Full code and dependencies here : https://www.box.net/shared/7yp3zthf8i

 

In this series of blog posts i would like to illustrate a number of techniques myself and the teams i work with regularly use to produce high quality software that delivers to the end user requirements.

The teams i work with and put together tend to come from the agile side of the software development camp. I will blog in coming weeks about requirement gathering and interviewing clients conducting workshops and other more ‘business’ focused techniques but i would like to start of with some development focused posts.

In the next 2 posts we will be using:

Example

Enough talk , more action …

Below we have a simple example of a story which has 2 acceptance criteria defined in the remainder of this post we will cover the shallow dive. In the second post we will then dive deeper implementing the service layer and the persistence layer.

Tools

A quick note on tools we are using visual studio 2010 and Resharper , trying to do this sort of work with out Resharper is like trying to run a marathon with a broken leg you can do it but it will hurt lots and lots. This is so true that when i do contract work i have my own personal licence just in case the client doesn’t have Resharper, Generally by the time the contract has come to an end the whole team is using Resharper, it is that good a tool.

Story :

As a HR Administrator

When a New Employee starts work

Then I Expect to be able to register there details on the HR system

Acceptance Criteria :

  1. As a HR Administrator

When i create a new record for a Employee

Then I Expect  to enter the following information

  • FullName
  • Date of birth
  • Address

2. As a HR Administrator

When have entered all the employees details

Then I want to press save

And I Expect to see the employee on the employee list view

Lets get straight to some code

As usual we start with a class library with no framework or references we will be building this example in a purely emergent fashion.

 image

Ok we have introduced some intent into the test with the name of the class but let us remember it is up for grabs to rename later , the name we have currently chosen will suffice for now and will get us going , as we explore the requirements and intent. (Tenet: Its ok to be wrong, as long as what you decide is good enough to allow you to move forward).

 

image image

Next we add a operation to represent the intent of our test and decorate it with the Test attribute remembering to add the TestFixture Attribute to the class declaration. We then need to add our testing assemblies i have chosen to use NUnit and some of the NSpec extensions that have been rolled into the NBehave Project. (Tenet: You don’t need it till you are driven to it , wear blinkers, ignore your pre knowledge.)

image image

So now we start to get into the implementation itself so we next write the story adding reference to the StoryQ dll, Resharper helpfully highlights the unimplemented steps in red, so lets Alt-Enter on each and resolve it.

image

so using Resharper and IntiliJ Mappings we can click on each red unimplemented method and choose ‘create method’ option 2.

image image

We then have a method stub for each step in the story and we are now in a position were by clicking on Resharper ‘yellow and green test icon we can run the test and get our first set of output.

image

So having run the test we can see that all the steps are pending so now we need to move on and implement the steps, the framework knows that they are pending because of the ‘NotImplementedException’ which is thrown, you will recall Resharper but those in each method by default for us.

 image

The next step is to conceptualize the UI , so lets set the ‘EmployeeName’ property on the ‘conceptualized EmployeeCreator’ form.

image

So using Alt-Enter on Resharper we add a field and tell the system we will be using a Mock of type ‘IEmployeeCreator’ so we now need to get our mocking library my personal favourite id Moq.

image

With the Moq reference in place and our interface created were ready to implement the property on the interface, and verify it gets set on the mock, making its behaviour explicit within the universe of the test.

image

Next we set up the property on the Mocked View so we can set it, following the intent of the step. (Hint: Calling ‘Object’ on a Mock(Moq) returns to you the real object and then you can call the properties and operations as if it was a concrete object which in turn will obey your setup directives.

image

Next we run our test and it complains that the interface ‘IEmployeeCreator’ is not public so we fix that and re-run.

image

Back in the IDE we get driven to code, in the next step we enter the employees address now in reality this would probably be broken down into country , state, zip code and so on for the sake of this contrived example we will keep it as a simple string as opposed to pushing through to a address object. Note on this is that even in a production environment we might find ourselves well served just to implement a simple string and then once we have the test passing refactor this to a Address object.

 

image

We can see above that Resharper is telling us that the address property is not implemented so again we alt-enter on the method name and Resharper implements a property for us.

image

Again we follow our work flow and run our tests , then we implement the next step, the Date Of Birth which again drives out another property leaving us with:

image

The piece that i have delayed showing you as i did not want to distract attention from the work flow, is that Moq has a really useful piece of functionality for stubbing properties. Now we have more than 1 property on the Mock of the IEmplyeeCreator interface we will take advantage of this functionality, to do this In our set up method i have now add the following line of code:

image

This effectively creates automatic properties on your Moq object for each property expressed on your interface. This is very useful when we don’t want to verify a property or express some expectation on the event that property is set or get.You can think of it in terms of short hand for a Stub.

So where are we, and what has our story have produced so far?

We have the concept of a view double by mocking the IEmplyeeCreator  Interface , we will use this to define the UI implementation object a little later. We have on this interface defined a number of data items that we need the user to set, we have ‘for now’ used a mock all properties method on the Mock to do this as we are not concerned about these properties at this point.

The Last mile

Lets move to the next step in the story and a re-read it and it is talking about a save button i decide im uncomfortable with that because it is not abstracted enough and is implying implementation which as ‘Story Author’ I don’t want to really think about, So i click on the operation name and press ‘F2’ and Resharper opens its rename dialog.

image

I rename the step like so :

image

So having changed the semantics i move on to the implementation,  there are a number of things i can do here but as i like to keep my implemented UI as thin as possible i decide to raise an event to trigger the save operation, this also allows me to abstract if i so desire later the save operation to a outside collaborator such as Model / ViewModel or manager/ controller.

Ok so this bit is a bit of a big step but its were we finally start to see a connectivity point into the wider system be introduced.

First of all as discussed above we raise a RequestSave Event and at this stage i decide there isn’t a good reason to do anything other than cast the form to a interface which represents the data only and pass it out as a Argument in the eventArgs, this may change later but remember were wearing blinkers and doing only what we must to implement the behaviour.

image

We set up an event handler on our Mock / stub (View double) as we have no need at this stage for an orchestrator like a controller or presenter or such , but again we may do later.

image

image

As you can see above we have finally introduced our adapter , and although this is a long post in a production environment this is about 10 minutes worth of coding effort, for a pair with knowledge of the technique.

Ok so now we must mock our adapter and we must bring in our data interface and build our EventArgs class.

image

 image

With these pieces in place we can see that when we run our story we are nicely taken to the the final step.

image

To Recap
  • We have represented a Behaviour in a story
  • We have created a View Double
  • We have created the concept of the user data
  • We have created a action and a interaction between to members of the code domain the view and the adapter which is the entry point to our larger system
  • We have one step out standing before we can get a green passing bar and start driving deeper into the system via the adapter.
The final Step in our shallow dive

 

image

We now set up our expectation in our final step again our entry point is the form double and in this case we are using the NBehave Extensions. Note this is a slightly modified copy of the extensions that i worked on with Agile Workshops Ronnie Barker, they can be downloaded from :http://blushpackages.com/downloads/Nbehave_extended_with_source.zip or you can use the production NBehave extension form the NBehave Org.

 

This leads use to implement another event on the form double.

image

With this full collaborative exchange with the Adapter , i now feel driven to implement this object as such our next step is to create a concrete adapter. We let Resharper do the heavy work by adding the interface to the implementation list of the new class, and pressing alt-enter on the red squiggly line.

Once this is implemented we can go back and remove our service adapter mocks and use the concrete class. Principal Mocks are not always for life  , quite often they allow us to move forward till our design has emerged from our intent enough to demand a concrete implementation of the object.

This drives us to a decision point in our test intent originally we had this step which we had satisfied with a step declaration like so:

image

So in simple terms we wanted to know when the record had been saved in the service , so after going back to the story [ And potentially the Story Author / BA ]it is now plain to us that actually we don’t care about this step , what we care about is that when we ask for the list of employees we want to see the employee details in it. So we can safely remove this step. Principal don’t panic to much about your understanding of the story at the start the understanding will deepen and emerge as you move forward with the implementation of the story.

image

So as we can see above we now have a concrete Service adapter which as you will see in a moment leads me to implement a concrete employee object which is also visible in the above screen shot.

 

image

So if we re run our tests having implemented the concrete adapter we get to our NotImplmentedException as you can see our behaviour is driving us each step of the way.

 

image

So lets implement these method and get back to a clean state.

 

image

The next thing we do we raise the RequestEmployeeList event on our View Double.

image

Next we implement the handler for the RequestEmployeeList event and we call the GetEmployeeList from the now Concrete Service adapter.

This then drives us after running the tests to implement an internal storage in the adapter like so :

image

This then leads us to run our tests and we get yes a Green Bar thus we have completed our shallow dive between the form double and the client side end point the adapter.

image

I fully appreciate this is a long post but as stated above in a production environment with Resharper and keyboard/short cut skills this is no more than 10 – 15 minutes of work.

With out these skills and tools this is a lot longer normally measured in hours.

I hope this has been helpful. Next time we will look at implementing the View Double as a winform application using Unity IOC.

Full code and dependencies here : https://www.box.net/shared/7yp3zthf8i