TDD – Just enough code…

I’ve spoke and demonstrated on my YouTube videos about only putting in enough code to a project to get a failing test passing, even if the code you’re adding isn’t going to make any sense to how it might end up later on. It really sounds confusing and I’m going to try and back this up with an example. The more I can emphasize this point, the more it will help in keeping tests high and code lean and fully exercised by tests.

Consider the following. I’m going to create a HttpServer and part of my first test, we will see the following code:

HttpServer server = new HttpServer(80);
server.Open();
server.Close();

In that code, we have 1 undefined object ‘HttpServer’, 2 methods, and 1 constructor. To add the most minimal code to get the test passing, I just need to define the class and stub out the methods. The methods will not contain any code, neither will they have return values. My test is now passing.

To further developer this class, I need to keep adding more tests that initially fail, to detail its behaviour. So another test would be written and the code then filled in the HttpServer class to pass that test – and only enough code to pass that test.

If I did not write just enough code to make the test pass and instead I just went on and fully implemented the ‘obvious’ code that should go in those methods, then what would happen is I would be implementing behaviour and fine details of the class that do not have any tests for that behaviour.

So once there is enough code in that class to pass my test, I stop. Then I would continue to think of what other behaviours I want from the HttpServer. I’d then write a failing test to verify that behaviour, and then write the code to pass that test.

This principle of only writing enough code to make the test pass is key to maintaining the TDD flow.

Just to summarize, stick to these two principles:

    • Only add code when a test is failing.
    • Write just enough code to make the failing test pass – nothing more.
      Advertisements
      This entry was posted in Agile, TDD. Bookmark the permalink.

      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 )

      Twitter picture

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

      Facebook photo

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

      Google+ photo

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

      Connecting to %s