Measuring Simplicity in TDD
Historical article · Originally published January 19, 2011; technical details may be outdated.
Uncle Bob talks about priorities when changing code functionality according to a failing test (‘tranformations’):
http://cleancoder.posterous.com/the-transformation-priority-premise
he asks:
- Is there really a priority? (I think so, but it might be more complicated than a simple ordinal sequence)
- If so, what is the principle behind that priority? (some notion of “complexity”)
- Can it be quantified? (I have no idea)
Yes. There IS a priority and he is right. When I teach my students how to solve things, I talk about what it means for solutions to be simple. I quantify and measure simplcity of a solution by:
- How high is the code in the function? the closer it is to the beginning, the simpler it is
- How indented is the code? the less indentation, the more simple it is
- How wide is it? It should be as narrow (short) as possible, but still be readable
- How many ASSUMPTIONS does it have? the more assumptions it has, the simpler it is (this goes to Uncle Bob’s idea of tdd making code more and more generic as it progresses which fully agree with). For example, if you can assume on the length of the input, the code will be simpler than having to find the length.
On the test side, I always try to ask:
- What is the simplest test that proves there is something wrong with that code?
- How can you prove that the code is making a hard coded assumption?
- Did you fully “solve” the last test? or did you “cheat” by making an assumption in the code? if so, keep writing tests on that assumption until you can move on to the next “task” in the requirements - where there are no assumptions left in the code that disagree with the requirements
3comments
Comments from the original blog, kept for the record. Commenting is closed.
Hi! By "How high is the code in the function?" you mean how short is the function? I didn't really understand... Can you please detail a bit?
If I were to point someone who wanted to understand how to start TDD this would be the article. Short, simple like and to the point just like a good test.
Igor: by 'how high" I meant - "how high in the current function is the NEW CODE you're writing to make the test pass.
if you add a line close to the method's start, that's simpler than adding it lower in the method body.