Top-down vs Bottom-up TDD

Switching from “normal” coding techniques to TDD can be difficult but once you were able to make the mental switch you realize that there is more substance to TDD than just the usual hype phrase “red, green, refactor”.

Test Driven Development can be approached from a various set of angles (some of which probably I don’t even know…yet). Martin Fowler divided TDD practitioners in two categories classics and mockists (details here)Coming from a background where unit testing heavily relied on mocks for perfect isolation of the tests I consider myself to be a mockist TDDer.

While doing TDD you can practically start anywhere in the system from any component/class you like (assuming here that a basic design is already created, and you have a rough view of the system), however the way you go about it, top-down, bottom-up or from the middle has its peculiarities.

Recently I was implementing a design using bottom-up approach and came across an interesting maintenance problem. When you code from the bottom, you are designing the interfaces of the objects to suit your immediate needs, that is take the simplest solution that works. However when reaching the upper layers you may notice there are forces that push on the existing design of the interface and most probably will change it if it makes more sense. Thus you need to do some maintenance work.

Lets take a very simple example. Consider an MVC3 application that has the design in the image bellow (this is the simplified version, I omitted the interfaces for brevity).

D1

I started off with implementing the CompanyService which initially looked something similar to this:

Drawing1

When it was time to move on to the controller things have changed a bit. Coding the controller has forced some changes on the interface of the CompanyService (see bellow) that seemed more appropriate. If I had started from the controller first I could have created the service interface properly from the start and avoid some refactorings in code but also in the respective unit tests.

Drawing1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s