Lately, it seems, I’ve had a case of coder’s block, not exactly know how to start writing a specific piece of code. I understand what needs to happen, yet, I’m hesitant to start. My brain is trying to refactor code that I haven’t even written yet. In addition, there are too many options to choose from. Since deadline pressures won’t wait for the ultimate architecture or design, I start coding prematurely. As a consultant, the last thing I want to do is to leave a maintenance nightmare for the next person.
So I reluctantly start to code. My fingers pound at the keyboard producing a working chunk of code. Write. Compile. Test. Debug. Many iterations later, I have written a non-optimal partially complete solution. More coding ensues. I start noticing similarities with code I just wrote. I start to copy an existing section of code, but instinctively, my gut screams at me “Don’t do it! Refactor!”.
At this point, I have two choices. The “just get it done” mentality wants to finish the code, without refactoring. On the other hand, the “perfectionist” mentality wants a cleaner design by either refactoring the existing code or rewriting everything. Depending on the situation, each option might be valid, depending on the specific circumstances.
However taking either of the two choices to an extreme is not the way to write software. I may look like a hero in the short term if I choose to just bang the code out. But when the next person comes in to either fix bugs or enhance the system, they will likely look at the code and wonder what the heck I was thinking. In sharp contrast, if I choose to refactor to the nth degree until I have achieved some level of perfection, I will likely miss my deadlines. Maintenance programmers, however, will love to work on the code I wrote.
Balancing the need for speed and the need for a clean design is not trivial. It is a task that must be learned with hard work, trial and error, lots of mistakes and experience. This learning process can be sped up by reading books/articles/papers written by gurus, having a mentor comment on your code or by pair programming with somebody who has plenty of experience.
In an ideal world, refactoring until the perfect solution is discovered would be the way to write software. Until that time comes, learn to write software that balances between the extremes.