Putting the problem before the solution

Recognize the following scenario? You get a description of a non-trivial problem. Before you’ve even heard the full description, your problem solving brain starts working on a solution. After a few quick adjustments of your idea, you feel you’ve successfully solved the problem and start coding.

I bet you recognize it. I bet you do it all the time – I sure do. If you have experienced this, I’m sure you’ve also noticed that this first attempt at a solution tends to be incorrect, especially for more complex problems. Often you realize later that you didn’t completely understand the complexity of the situation.

This is one of the reasons why I choose to write unit tests before implementation –  to ensure that I understand the problem before I decide on a solution.

Test-Driven Development is about design, but also learning

As you perhaps have heard, Test-Driven Development (TDD) is not really about testing, it’s about design. That is true. It encourages you to think about your  code from a usage perspective first, rather than an implementation perspective. You write code that uses the implementation-to-be before you write the actual implementation. The interface of the code to be written is colored by how you want to use the code, rather than how you plan to implement it.

While Test-Driven Development is about design, is also about learning. It makes you to think of the problem before the solution. I find the following rule of thumb helpful.

If you cannot describe the wanted behavior in a test method name, you are not ready to start coding.

If you follow this rule, you vastly reduce the risk that you waste your time on implementing a premature solution.

An old world map, by Rosario Fiore

A map reflects the ones understanding of the terrain.

Implementing the first solution that comes into your head would be like running as fast as you can while looking at your feet, not realizing if are running the wrong way. When you later realize that you’re not were you wanted, you will have to choose if you want to live with being in the wrong place, or spend even more time going to the right place. It’s more effective to pause for a few minutes, and then run to the right place from the beginning.

Another way to see it is that your understanding of the problem is your map to the problem. The more correct your map is, the more likely you are to end up where you want to.

Leave a Reply