Good code seldom emerges right away

I often see people struggle to write good code from line number one. Instead of making progress on a problem they need to solve, they get caught up in designing the solution the “right way”, tripping over a myriad classes, interfaces and what not. This is especially the case with those who are new to programming - they have been taught about the importance of clean code, and try their best to follow what they have learned.

While the intention here is right, good code seldom emerges right way. Good design and good code, evolves from bad code, just like how a diamond emerges from the rough. Trying to write perfect code from the start often leads to over-engineering.

It’s not easy to build both the desired functionality and the correct design for it simultaneously. In many cases, the desired functionality itself evolves as you start implementing a solution. We don’t have to place this artificial constraint on us at all.

It’s easier to have two modes of operation when you’re coding. In the first mode, you will just bang out some code that nails the basics of the desired behavior. Once you’re fairly certain about the direction you’re going to take, write some tests around your functionality and switch to the software-engineering mode to refactor and redesign the internals. The tests will help to ensure that your refactoring does not break the correctness.

This approach is not an excuse to write bad code. It merely separates the problem solving and the design concerns so that one doesn’t need to focus on both of these at the same time. It’s important to emphasize the importance of refactoring as an important step towards the final solution and ensure that bad code is not shipped to production and conveniently forgotten.

This post was written by Kishore Nallan