What Is Clean Code?
There is much to be read about how to write clean code. However, sometimes it’s important not to miss the forest for the trees and focus on what truly matters. So, what is clean code actually all about?
For me clean code is about three core qualities: correctness, readability, and ease of change.
Correctness
If you ever had to work with a bug-ridden code base, you know how frustrating and time consuming that is. Even the smallest of changes fails three times, because the existing code just doesn’t work correctly. Countless hours have to be spent testing and fixing code. Still, in the end the customer will find even more bugs.
So clearly correctness has to be one of the core qualities of clean code.
Readability
As software engineers we spend the vast majority of our time reading code. If the code can be read and understood quickly, we can work quickly. If the code can be read easily, we can focus on our changes.
Ease of Change
Code is changed frequently. The easier this can be done the better.
One key element to make code easy to change is to ensure it is easy to read. Therefore never try to predict future changes and prepare your code for it. That will add additional code and complexity to your code, which makes it harder to read and thereby harder to change.
What About Other Aspects of Code?
Everything else that you can do to your code does not improve the quality of your code. Worse – it probably adds distracting clutter and hurts readability.
But What About Performance?
The one item notably absent on the list is performance. Why is that?
Optimized code almost by definition is more complex. Complex code is harder to get correct, harder to read, and harder to change. It violates all three core qualities of clean code. Hence optimized code is worse code.
Optimization is not something that makes code better. Optimization is a necessary evil we have to resort to in rare cases when we know for sure that it is absolutely required. These situations tend to be a lot rarer than we assume, they tend to be in different places from what we assume, and we have to be very aware that optimization always comes at a cost.