Saturday, January 05, 2008

Dear Microsoft

I thought it was very sporting of you to somehow break your MSDN subscriber downloads page for your flagship IE7 web browser:

Broken Download

But not for Firefox:

Firefox ok

Well done! I didn't even realize that the site had any problems at all until I switched over to my virtual machine of XP from Ubuntu in order to download the ISO I needed via your custom file transfer application. Why do you insist that I use this at all? It seems really odd.

Anyway, perhaps I should just try to get your File Transfer Manager to run in Wine and I could have a seamless experience browsing your web site from a proper OS....

Love and hugs,

Stu

Sunday, February 11, 2007

Damn Skippy

From a conversation whilst pairing with a client developer as we attempted to test infect some legacy code last week.

Me: Phew! Well, that little bit is under test now. We can start to fix it up now.

Client Dev: That seemed too hard....you know, if the guys who wrote that had had to put in tests as they went, the API would NEVER have looked like this. It would just have been too painful to work with.


It really is nice to witness the penny drop. True job satisfaction.

Monday, February 05, 2007

Test Code and Production Code – two distinct beasties

There are some common qualities that production and test code must possess in order to enhance their status as ‘good code’. Typical dimensions which one could apply may be conciseness, clarity of code, performance, elegance and extensibility (the list goes on). These are all good methods of assessing ‘good code’. However what differentiates good test code from good production code is not so clear when only these traditional qualities are taken into account. It may be more useful to consider what the drivers for the two type of code are.

For production code, these traditional values are useful, but cannot be assessed meaningfully if the code does not fulfil a business requirement. Ultimately this is the only driver of production code – it has to get the job done for the business. If your widget selling app for Widgets R Us cannot help to sell widgets, then no one will really care how speedy, elegant and extensible your Ultra Widget Framework is. The business code also needs to be robust enough for the business demands to allow the application to stay up and running cheaply enough for them to get a return on the build. It is a harsh world we live in and production code has to cut it in an unjust world.

So what about the test code? Test code has a different set of drives which compliment the production code. The primary driver is to assist in delivering high quality production code which robustly meets the requirements of our client. To this end the code also needs to drive the design and document the expected behaviour of our production code.

Driving the design of the code pushes the code towards delivery of production requirements, but this is only part of the story. Test code can used to accurately model the expected behaviour of the system and ensure that all key behaviour aspects of the system really do behave as per the requirements. By driving the design of the code with tests the system can meet the key delivery and quality drives of the code, but allows the developers the opportunity to make other improvements which improve the traditional values of the code. For example, a developer is more likely to refactor towards an elegant pattern which is emerging when a safety net in place than without one. If our tests measure performance then we are more likely to improve our performance qualities.

The test code is also a driver to document the behaviour accurately and clearly in order to provide a suitable level of traceability to the team and the stakeholders to demonstrate that the business need really have been met. When the test code is clear and comprehensive then the application benefits from not only the traditional test safety net, but also executable documentation that can highlight where and how the application has veered from the course of the business requirements.

So do traditional values not matter any more? Not at all - these values are crucial to quality code – in test and in production. However, you may assess the values differently in test and production code based when you consider what the code is driving to achieve. What may be reasonable in production code may be unsuitable for test code, as the application of a particular approach may obstruct the drives of test code to drive the design of the production code or clouds the documentation qualities of the test code by making a test less clear.

Put another way, just like in acting, it is important to consider your code’s motives first and then apply the traditional values in the context of what the code is trying to achieve.

Tuesday, November 14, 2006

Where there's no sense, there's no feeling

I finally got a chance to go beating again on Saturday. I help out as a beater at a couple of the local pheasant shoots; a good day's beating is about as much fun as you can have in the countryside with your trousers on!

The season started over a month ago now and I have already been to one shoot. Unfortunately though I have been unable to take Lyra with me due to her suffering from 'lady dog problems'. Luckily for both of us this is all over and done with now. So we eagerly headed off to Ram Alley for a spot of pheasant chasing.

As this was Lyra's first outing of the season, I was a little nervous about how she would perform, would there be any signs of canine resentment for being left behind on the previous shoots? Would the lack of training during those summer months I had spent away from home show at all?

The first drive put all my fears to rest. I had to work Lyra through a patch of maize. This sort of cover crop can cause problems - dogs get very excited chasing through the cover looking for game (it probably feels like one of those jungle chase scenes in Predator to the dog) and the lack of visual contact can mean you loose control relatively easily. But she did really well - even retrieving a bird that had been overlooked by the pickers up :-)

And so all through the day we went from good to better until we got home. Only then was it clear that my, by now dog tired, hound was finding it hard to settle down on the carpet. On closer inspection we realized that, although her paws and muzzle seemed completely immune to nettle rash, the inside of her ears were not. All inside both ear flaps she was read raw with nettle rash!

Clearly she was having so much fun during the day that she hadn't noticed that her ears were glowing. I think I can understand though. Lyra is a working dog, and she is driven to work in the same way that many of the truly good developers I know are driven to code. Imagine a world where coding was only permitted September-January and you could only get access to a really useful computer 2 or 3 days a week at best. This is what it is probably like for Lyra (shudder). If this were the case, I don't think you would stop coding if you got a paper cut on a couple of fingers...

Given the way the winter is going there will be nettles in the woods for a few weeks yet and there's no way I can leave the dog behind. So, now I'm surfing the net for nettle rash cures for Weimaraners...

Is the clutter in your test trying to tell you something?

We’ve all encountered it at some point or another. Your unit test is doing the job, but the test is so bogged down with setup code that it is impossible to see the wood for the trees. The interesting test code is in there somewhere, but where exactly?

The common causes of clogs in your test code are:

  • Complex object creation code.
  • Preceding interactions with the test subject.

Complex object creation is simple to deal with. You can create test fixtures to create the object for you, or better still you can refactor the code to try and simplify things a little.

But what about the interaction clutter? This is more subtle in the way that it insinuates itself into the test code. The clutter sneaks up on you. It demands more and more code to be added due to 'unavoidable' interactions with one object after another. Soon the useful to useless LOC ratio in the test case has tipped. Suddenly it becomes the norm that you should have N interactions in the test case to simulate calls to the database and N more calls out to other supporting services, even though the aspect of the code which you want to test has no real need to go through these extra steps.

For a particularly contrived example, lets imagine that we are building an online Pie ordering service for Weebl & Bob's Pie Delivery Service…and we are implementing it using WebWork.

We are in the final stages of implementing our pie ordering action. We want to verify that on execution the action invokes a number of support services:


public void testShouldOrderBobAYummyPieOnSubmit() {
PieOrder yummyPieOrder = new PieOrder(“yummypie”, 1, “for Bob”);
PieOrderingAction pieAction = new PieOrderingAction(orderService);
pieAction.setAction(Action.SUBMIT);
pieAction.execute();
assertEquals(yummyPieOrder, orderService.getLastPieOrdered())
}

But our test fails to run - it never reaches our orderService throwing nasty null object exceptions instead. But why? Looking more carefully at our execute method we make a number of discoveries:
  1. When our action executes, it actually loads our order from the database using its repository and the supplied pie-ID. This test doesn’t supply a repository or a pie-ID. So we buckle down and add it into the test.
  2. Weebl and Bob’s Pie Delivery Service often runs out of stock. So before we can allow our customer to order our pie we need to call out to our pieInventoryService to ensure that the yummy pie actually exists and is ready to be cooked for our customer. Grrrr. We add more support code into the test.
Now our test has become a bit of a monster:

public void testShouldOrderBobAYummyPieOnSubmit () {
PieOrder yummyPieOrder = new PieOrder(“yummypie”, 1, “for Bob”);
PieOrderingAction pieAction = new PieOrderingAction(orderService);
pieAction.setPieOrderRepository(pieOrderRepositoryMock);
pieOrderRepository.expects(once()).method(loadOrder)
.will(returnValue(yummyPieOrder));
pieAction.setPieInventoryService(pieAlwaysInStockStub);
pieAction.setAction(Action.SUBMIT);
pieAction.setPieID(yummyPieOrder.getPieD());

pieAction.execute();

assertEquals(yummyPie, orderService.getLastPieOrdered())
}
OK, so this isn’t the end of the world. But it isn’t so hot either in pastry-free, real world scenarios, this could be much worse. The problem here is that our implementation of execute has 3 phases:
  1. Load PieOrder
  2. Verify PieOrder
  3. Submit PieOrder

public class PieOrderPacingAction…{
public void execute(){
//Load pie order…
//validate pie order…
//submit pie order…
}
}
We really only want to test phase 3 in isolation. Someone has already implemented tests and production code for steps 1 and 2 – we don’t want to repeat ourselves.

Time to listen to the test. Our test code is suggesting that this is not an optimal implementation. We could choose to hide all this away in obscure setup code, or we could try to find a better way of implementing our code. So we pick the best option and look into the API of our actions and discover that we could implement this differently. WebWork supports actions which implement prepare() and validate() methods. Woot! We can move our code into these calls instead and simply our production code.


public class PieOrderPacingAction…{
public void prepare(){
//Load pie order…
}
public void validate (){
//validate pie order…
}
public void execute(){
//submit pie order…
}
}


The beauty of this is that, in theory we can chop up our tests.
  1. Our first set of tests check that the action loads the PieOrder during prepare().
  2. Our second set of tests prove that the action validates its order during validate()
    Given that the action has already loaded the order..
  3. Our third set of tests verify that the action will submit the pie order during execute()
    Given that the action has already loaded and validated the order.

So our test case looks like this now:



public void testShouldOrderBobAYummyPieOnSubmit () {
PieOrder yummyPieOrder = new PieOrder(“yummypie”, 1, “for Bob”);
PieOrderingAction pieAction = new PieOrderingAction(orderService);
TestUtils.setPrivateField(pieAction, “pieOrder”, yummyPieOrder);
pieAction.setAction(Action.SUBMIT);

pieAction.execute();

assertEquals(yummyPie, orderService.getLastPieOrdered())
}


Those following closely will have noticed a call to set the pieOrder field via reflection. So why did we set the private field here (using evil reflection of all things!)? Well, this comes back to not test driving the code the wrong way. We could have added a setter to allow a more traditional way of setting the object state. However, this is not useful to the real world. We are only setting the internal field in order to get our object into the correct state to test it. It is less evil to use reflection to put an object into a valid state for a test situation than it is to add access to internal state legally for all code.

So what are the issues that we have to watch out for here?
  • Obviously the test is now more tightly coupled to the implementation details of our test subject. If we change the internal structure of our object, we could well break our tests. We can mitigate this by not making our object complicated. In this example we only reach into our object to set one field. Try and keep things this simple when using this technique
  • There is a risk that the tests don’t join up properly. If you are going to reach into an object to set its state, you must have corroborating test cases which prove that the object is in fact in this state at the end of the preceding calls in its lifecycle. It may also be worth writing a small number of ‘integration tests’ which run the object through the whole call cycle (here, prepare -> validate -> execute) in order to demonstrate the expected behaviour of caller and to prove that you got things right with the lower level testing.

Thursday, October 19, 2006

Buried Intent. Bad for campers, bad for TDD

Remember that your test code is not production code. The purpose of your test code is to prove that your production code works and to provide live documentation. Qualities which make good test and production code are not necessarily the same. For example, it is important that a test case clearly demonstrates the expectations of a test case inline. This is especially true when working on an XP project, as these tests are your primary means of documenting the expected behaviour of your test classes. If another developer cannot read your tests easily and determine what was intended of the production code then trouble will ensue

Consider the following test case:


public void testValidateOffPeakUserConnectionRejectedDuringPeakTimes() {
ClientConnectionRequest connectRequest = new ConnectionRequest("bob", "12345");
setMonitorExpectations("bob", "Some account", "12345", ON_PEAK, true, false, true);

boolean requestResult = connectionMonitor.validate(connectRequest);
assertEquals(false, requestResult);
}

Superficially, this test seems to be OK. The test is short and sweet, and we are checking that our monitor rejects the request. But is going on exactly? Well, to work this out we have to dig down into the setMonitorExpectations method. More information is revealed:


private void setMonitorExpectations(
String clientName,
String accountName,
String clientId,
boolean introductory,
boolean unlimited,
boolean offPeakOnly) {

UserAccount account = new UserAccount(12345L);
account.setAccountName(accountName);
account.setClientName(clientName);

buildAccountType(introductory, account);

repositoryMock.expects(atLeastOnce()).method("find").will(returnValue(account));
repositoryMock.expects(once()).method("isUnlimited").will(returnValue(unlimited));

if (offPeakOnly) {
account.setAccountRestrictions(AccountUsage.RESTRICTED);
repositoryMock.expects(once()).method("getAllowedConnectPeriods")
.with(eq(12345L),eq(clientId)).will(returnValue(offPeakOnly));
}
}

Oh, so we are setting up a bunch of attributes of the account, conditionally flagging the account as restricted, and then going on to add an expectation. But we still don't have the full picture, as there is yet another call out to buildAccountType.


private void buildAccountType(boolean introductory, UserAccount account) {
if(introductory) {
account.setAccountType(AccountType.INTRODUCTORY);
}
}

Now we have a a number of problems.
  • Although the test code works, and is compact it is failing to fulfil the role of documenting the production code clearly. In order to determine what my test methohd is trying to prove I have to dig down a number of levels.
  • I suspect that the helper method is actually too rich for this method. There is conditional logic in there to change the expected test behaviour based on the test situation. This may be acceptable in production code, but conditional logic has no place in test code.
  • The fact that the interactions with other objects are buried in the helper functions is also hiding potential issues in the production code. In this case it is the repeated calls to the repository. By inlining the expectations it would be more obvious that the classes have a chatty relationship, and this could be harnessed by changing the test expectations and driving the production code to become more efficient.
This is a natural trap which we can fall into when we are constructing unit tests. Our IDE allows us to extract methods so easily these days that we often find that we are extracting "common code" from our test calls because we believe that this is helping to keep the code base compact and efficient. In fact, this naive refactoring can case real problems. Now that our test code is less clear to a casual reader, the overhead of maintaining the test suite could rise!

Ways Out Of this Situation?
In this situation the simplest route out is to inline all the buried methods and step back. In this case we initially end up with:


public void testValidateOffPeakUserConnectionRejectedDuringPeakTimes() {
ClientConnectionRequest connectRequest = new ConnectionRequest("bob", "12345");

UserAccount account = new UserAccount(12345L);
account.setAccountName("Some account");
account.setClientName("bob");

if (ON_PEAK) {
account.setAccountType(AccountType.INTRODUCTORY);
}

repositoryMock.expects(atLeastOnce()).method("find").will(returnValue(account));
repositoryMock.expects(once()).method("isUnlimited").will(returnValue(true));

if (true) {
account.setAccountRestrictions(AccountUsage.RESTRICTED);
repositoryMock.expects(once()).method("getAllowedConnectPeriods")
.with(eq(12345L), eq("12345")).will(returnValue(true));
}

boolean requestResult = connectionMonitor.validate(connectRequest);
assertEquals(false, requestResult);
}


This is clearer than we had before, and when the method is rearranged and the account creation logic extracted into a helper method we end up with:


public void testValidateOffPeakUserConnectionRejectedDuringPeakTimes() {
UserAccount account = buildAccount(
12345L, "Some account name", "bob client", INTRODUCTORY, RESTRICTED);
ClientConnectionRequest connectRequest =
new ConnectionRequest(account.getClientName, account.getId());

repositoryMock.expects(atLeastOnce()).method("find").will(returnValue(account));
repositoryMock.expects(once()).method("isUnlimited").will(returnValue(true));
repositoryMock.expects(once()).method("getAllowedConnectPeriods")
.with(eq(12345L), eq("12345")).will(returnValue(true));

boolean requestResult = connectionMonitor.validate(connectRequest);
assertEquals(false, requestResult);
}


Note that this refactored test is really not much larger than the original. However the difference is that the test expectations are clearly visible. As a result, the developer is more likely to be in a position to improve the code. Here the mock object interactions are showing that we have an overly chatty relationship with another object. This could be a sign that we are suffering from the 'feature-envy' anti pattern in our production code, which in this example could lead to us making bitty calls to the database and could become a performance bottleneck. By exposing the relationship explicitly in the test case, we can now choose what to do about the situation.
  • Live with the problem - this is not an important feature
  • Change the expectations to drive improvements in the production code. It would now be easy to change the test case to forbid the look up calls to the repository and drive the production code down a more performant path.
  • Break up the method under test.

Saturday, September 16, 2006

The Testing Anti-Patterns Drafts Vol. 1 (draft2)

George and I both consider ourselves fortunate enough to work as members of teams where TDD is practiced by default.

There are two reasons beyond the obvious as to why we find it relatively harder to code in a non TDD approach. Test Driving our code enhances our vision on how to design/model/instrument the application's universe. Also, starting with a test means work begins and ends with coding, not meetings, discussions or modelling our vision in pictures bound to be proven unrealistic when the first coding bottlenecks arise.

This is not to say that discussions or modelling are intrinsically bad things, a good brisk white board discussion can really help – but don't ever forget that this is a relatively abstract activity.

Tests have a much closer relationship with your code that allows you to discover and document the behaviour of your system in a much more detailed manner. In fact it is the close relationship between tests and code that can lead to problems. This relationship must be kept in balance if the process is to be successful.

Production code is the bread winner. This is where your business value lies. However, due to the nature of the TDD process, the production code is also somewhat dim-witted; it doesn't really have a clear vision or motivation in life. The test code is there to explain to the code what is expected of it and to highlight any mistakes the code makes by identifying in a precise manner why the code doesn't quite do the right thing and to point out how to head off in the correct direction. In some respects this could be likened to the relationship between a boxer and his trainer. Ultimately, it is the boxer who has to go into the ring and win the fight, but it is the trainer who gets the boxer into the zone mentally and physically.

Another equally important role of the test code is to document the expected behaviour of the production system. This is fantastic! Suddenly, the technical documentation is no longer a static and dusty tome on a shelf, rather an ever accurate and clear guide to what the code really does. If your code is not fit for purpose, this should be made glaringly obvious in your tests, and by changing your documentation you should be able to change the behaviour of your code to make it do the right thing in the right way.

However, we don't live in a perfect world and testing properly is not easy, despite the presence of opposable thumbs and shiny new Macs. Once you get past the simplistic examples and into the real world you find that it is difficult to write effective tests, and often the tests are much harder to craft than the actual code. In many ways, this should not come as a surprise. When you write a test, you are attempting to satisfy a number of aspects of the system: quality, design, documentation. And all of this expressed though the medium of a software language!

So, what makes our tests go bad? There seem to be a number of patterns starting to emerge, but to list them all here is going to take too long – I think George and I are going to have to break this out (hopefully with lots of assistance from our friends ;-)). In my mind the coarse categories of TDD anti patterns are:

  1. Driving the code the wrong way.
  2. Hiding deficiencies in the code.
  3. General test smells

Test Driving The Wrong Way

This is the situation where your code starts to bend towards the test code to meet requirements of the testing framework rather than to meet the needs of the application. Examples of this include:
  • Adding calls to your production data layer code to allow setup/teardown/query operations which are not required by the application.

  • Providing access to properties which should not be made visible normally (this is what George is getting at with Design Pervasive Testing)

  • Forcing the use of IOC where in fact it makes more sense to create objects internally or access static methods.

Clearly there is a sliding scale of smelliness here. Overuse of IOC is not really such a bad thing – the code will still function as required. It just leaves you thinking that there has to be a better way.

Adding a deleteAllClients() method to your production code is a big deal though!

Sometimes, this can be sign that the test framework that you are using to test your application is not suitable, as switching to a different technology can help get around the smell.

For example - the use of DbUnit may make it easier to put your database into the correct state for a functional test and remove the need for the dodgy setup code in your data layer. Newer mocking libraries like JMockit can remove the absolute requirement for IOC based design patterns by allowing you to hook the creation of new objects and accessing static methods.

Hiding deficiencies in the code

This is where we seem to be suffering the most. It is very easy to hide problems in the code base instead of actually driving them out with your tests. Examples of this phenomenon:
  • Hidden behaviour. The production code performs a variety of complex activities in a given situation. However this is not clear because the test has buried the behaviour in deep in a number of (often obscurely named) helper functions. This is often a sign that you have too many complex relationships between your objects, or that the conversations the component has with its collaborators is overly chatty.

  • Supporting actors stealing the show. The test is so polluted with setup code that you can't actually make out what the test is trying to show you. This can often be a sign that the step is too complex.

General Test Smells

  • Badly named tests. This is especially bad when you consider the need to document the code through the medium of tests.

  • Inappropriate use of stubs. For example, stubbing a simple data type.

  • Etc.
In summary, I think we really need to care about the quality or our test code and learn to treat it quite differently to the production code, realising that the two portions of our code base serve different purposes in our development activities.

So...over to George to fill in some more blanks ;-)

“The Testing Anti-Patterns Drafts” is a collaborative effort between George “spring is overrated” Malamidis and myself which aims to identify cases of Testing gone bad. It consists of a single document that will undergo constant enhancements and modifications, in a “pair-authoring” manner, utilising our respective weblogs as the platform. We hope to get input from anyone following the document, our goal being to produce an interesting resource for the TDD, or Testing Oriented in general community.

Sunday, September 10, 2006

Son, it's time to be a geek...

This weekend a shiny new desktop arrived at the Caborn household. After many long months of procrastination, I finally bought a PC for my kids to use. The previous family PC had met an untimely end due to a spilt glass of orange juice about 6 months ago.

While the kids were at school I spent a nice geeky morning setting it up for them and now Heather is happily playing preschooler games and Skyping to my laptop downstairs. Fantastic.

My son wants to be a computer geek like his dad when he grows up. Well, not exactly like me; he plans to drive a DB7 and be a rock star Mondays and Fridays. So, if he's going to lead such a cool life, he needs to learn to program. I'd like to do this with him, in the same way that my dad tried to teach me how to be an engineer by getting out the Meccano set. PCs are easy to get to grips with and Phillip already understands how to put together a logical argument.

At the age of six I think he may be ready to start to learn to program. The only question is: what language should we start with? I posed this question to a number of fellow ThoughtWorkers and, unsurprisingly they came back with a variety of answers!

  1. Lisp - "You should teach the guy a proper language and Lisp has everything in it"
  2. Logo - "There nothing more rewarding than drawing a picture with a turtle and it made me what I am today!"
  3. Flash - "Flash is easy to use and there's instant gratification - it is very visual"
  4. Lego Mind Storms - "Its just so cool".
  5. Java - Java is easy to learn and I'm familiar with it.
  6. Javascript - I can't remember why this was a good idea.
So. I'm not certain, but I think I may go with Flash. I like the visual aspects of flash and most of the games and silly things the kids love on the net are made with flash. Wouldn't it be great to write a flash game together including scanned artwork provided by Heather (age 4)....

Time to learn to do stuff with flash. I think I've got about a week before Phillip finishes his latest PS2 game and remembers that dad promised to teach him to code. Should be plenty of time to learn to do something cool in flash!

Tuesday, August 01, 2006

It's tiddly, it's a wiki...

It's TiddlyWiki!

I'm playing with this at the minute as a replacement for the myriad of little emails, .txt files and other crud that I scatter across my laptop. It seems very nice and extremely user friendly.

The appeal for me at the moment is that I can shove the whole lot onto a USB stick and keep it with me wherever I am.

Monday, July 10, 2006

On graffiti and broken windows

In his book Tipping Point, Malcolm Gladwell describes how graffiti and broken windows can have a dramatic effect on the behaviour of the residents in a city. For those of you who have not read Tipping Point (and I strongly recommend you read the book), the key premises go something like this:

Social change does not occur in the smooth linear way which many people imagine.

Often social values will suddenly transition or ‘tip’ from one state into another. Social change such as crime rates and fashion can often behave in a manner which is similar to the spread of diseases.

A tip can often be achieved by the compound effect of relatively benign factors.

Too much graffiti and too many broken windows can tip a neighbourhood from being a good neighbourhood into a crime ridden no-go area. Additionally, the behaviour of key individuals in a social group can make quite bizarre actions (such as suicide) not just acceptable in a group, but also fashionable and desirable.

In order to repair a problem, you need to perpetually guard against seemingly insignificant factors in order to effect change.

When the new york underground decided to try to clean up the crime and vanadalism on the tube network, they started with the graffiti. The thoery was that by cleaning up the appearance of the trains the feel of the tube network would be improved and people would start to feel more secure and crime would be discouraged. In order to clean up graffiti on their tube network they did it in a staged and defensive manner. A small number of trains were designated as ‘clean trains’. These trains were not allowed to slip and become covered in graffiti even though other trains remained ‘dirty’. The number of clean trains was exteneded in a sustainable manner at the rate the tube system could cope with until the problem tipped and became controllable.

There goes the neighbourhood...

Applied to neighbourhoods, the principal is that an area can hit a point at which there are so many broken windows and walls covered in graffiti that it can change peoples social values. It suddenly becomes 'OK' to break more windows and deface property, and this can move on to more serious crimes being committed once people get a taste for misdemeanours. At this point the neighbourhood has tipped and will rapidly go downhill.

In order to affect change and tip a bad district back into the light, it is necessary to actively repair broken windows and clean up graffiti, because without improving the environment that people live in there will not be enough social impetus to allow the residents to control and discourage antisocial behaviour.

Back in the world of software…


It is interesting to consider if the concepts of the tipping point can be applied to software? I believe that they can. Many applications are perceived by their developers and maintainers to contain either 'good' or 'bad' code. Good code is much cherished by the teams who maintain them – and they bring joy and happiness to the world. Bad code is a millstone around the necks of the maintenance teams and is painful to maintain. But how do we judge good and bad code?

A number of factors can come into play here, but the main dimensions that I feel developers and QA's tend to use to decide if code is good or bad are perceived design quality, and the number of defects in the code base. Poorly designed or ‘smelly’ code is the graffiti of software, and bugs are our broken windows.

Code Quality and graffiti

Code quality is interesting. There are a number of motivating factors which drive for high quality code. Primarily it comes down to the values of the team. If a team values good quality code, then it will attempt to write production code ‘the right way’. However, in any project there are a number of competing drivers which can hamper the realisation of the quality code.


In my mind the biggest anti-quality drivers are:

  • The fact that there is a tight deadline.
  • Members of the team who do not value quality code.
  • Working in a bad district.

The first 2 of these anti quality drivers are common fare. But what about the bad code district? Despite the desire of a team to write good code, they may well struggle if they find themselves in a bad neighbourhood. If the code contains too many code smells (there is a high level of graffiti and broken windows) you may well find that you are producing more smelly code.


Why? Because the developers have lost hope.

The motivation to write good code and behave is much reduced if every preceding developer has treated the code so badly. It becomes very easy for our developer to scrawl on the walls by writing a piece of smelly code or smash a few windows with the odd poorly handled exception because there are so many examples of this about.

The very same developer would be much more likely to run up some scaffolding or lay down the dustsheets with the odd unit test in a good neighbourhood, before going on to build in that new feature.


However, you can get on top of this and agile techniques can be most effective. For a start – agile methodologies value good code. They also build in checks and balances which look to defend against the failure modes of human beings. This is important. If developers were machine like, they would not care if they were working in a bad neighbourhood and so there would be relatively little impact on the quality of new code introduced there. However humans are influenced by their surroundings and your process needs to take this into accounts. A number of XP practices can help here:

  • TDD – this is essential to defend against the broken windows initially. You must not add to the problems in your run down area by recklessly adding code. Use the techniques outlined in “Working with Legacy Code” to gradually ‘test infect’ your code base.
  • Pair programming – two developers have more courage and are more likely to “do the right thing”. Pair programming is a very effective way of cementing the desired values of the team – you can even use this to ‘inject values’ into the team by clever choices of pairs. If you don’t do pair programming – try using design and code reviews to achieve the same effect.
  • Continuous integration – regular builds maximise the return on investment of the TDD by providing lots of regular feedback. This helps to build momentum which is essential to get is you are to tip your code from a run down neighbourhood into an up and coming district.
  • Code coverage – not strictly an XP thing – but an important guardian of your defended streets – build this into your CI system.
  • Acceptance tests – write them for the new features and get them into the build. If you have time you could try to retro fit them but I have never seen this work well. Better to add them as you add new features or modify bugs.

So – if you have the values and practice in place, how to you ‘tip’ the code base?

If the team values improving the code base and is supported, then you can make tactical improvements. Don’t try to repair the neighbourhood all at once. Rather identify the houses and streets which you repeatedly visit and isolate them. Fix the broken windows by building out unit tests and functional testing to cover just these areas and defend them against the rest of the neighbourhood. Once you have a module under test – defend it with code coverage and automated tests to allow you to spot any breakages and patch them up immediately. Do not allow these clean areas to fall. (todo – relate to the tube trains here).

So – we’re all done then…?

Well, not really. No neighbourhood stays clean and tidy without ongoing effort. You need to actively guard against the problems which can drag your neighbourhood back down to the skids:

  • Maverick coders who churn out vast amounts of poor quality code and are not controlled by their managers or team mates.
  • Project schedules - prefabs of code are hastily erected to serve a short term need. But are still there 50 years later. This is fine in the short term – but you must plan to repay your design debts in a timely fashion or the surrounding properties in your code will start to suffer.
  • False values. You will not succeed if your team does not truly believe in the values they are supposed to believe in. This is the biggest killer of all - as people do not perform at their best when their hearts aren’t in the job at hand.
  • Lack of policing. All too often there is not enough effort put into place to police your new district. If you don’t crack down on the perps who break builds and flout the rest with non-TDD coding, then you will suffer from a rising crime rate, more graffiti and more broken windows - "there goes the neighbourhood...”



The inspiration for this entry came from a discussion last Friday in the pub with Jon. He has already blogged about this, but I wasn't going to let that stop me ;-)