Recently, I’ve had a bit of a paradigm shift in the way I think about software development. Essentially, that shift is to only focus on solving the problem at hand and not to write additional code just in case it might be needed. Credit for this comes from the excellent RailsTips article, Just in Time, Not Just in Case. Now many developers are going to find this concept hard to accept. After all, you should be writing code that addresses any problems that may arise in the future. That is how you write robust code right? … right???
Well I had the same problem accepting this at first. I had already accepted that my code sucks, and that I could be a better programmer by not programming. However, the concept of solving the problem at hand takes this one step further by making you catch yourself before you go writing code just in case it might be needed.
You end up asking yourself: “Wait a minute, am I over-engineering this?”
The main reason for not writing code just in case is that it rots. Code that isn’t used still requires maintenance, it still has bugs in it, and it still needs to be tested. The key is to accept that every line of code you write will potentially add more bugs. Reducing bugs means writing less code. Writing less code involves finding the simplest thing that could possibly work. Remember as a software developer, you are you’re own worst enemy. I believe that’s what makes this concept so hard to accept, particularly if you already think you’re a rockstar programmer.
Another problem, is that the simplest solution isn’t elegant enough for some people. For example, the simplest solution might be to just to skip the first line when looping through a file because it stores headings and not data. But then the questions start; what if the data changes and the first line isn’t a heading any more? What if we have headings across two lines? What if the data is encrypted in an alien cipher … and so on. Right now, the headings are on the first line, and the code passes the test of reading the data with the headings where they are. Problem solved, move on now.
A good way to ensure you solve just the problem at hand is to take a test first strategy. Sure you can write unit tests and execute them in xUnit if all that is available to you. But really, this simply means:
- Write the test first;
- Write enough code to make it fail second;
- Write enough code to make it pass third;
- Move on.
Note that writing the test may simply mean writing the test out in English (or your preferred language). Automated unit tests are still a luxury.