There are various heuristics we use to drive towards the north star of clean code. In this short essay I touch on a few heuristics, while trying to answer the question — why do these heuristics exist in the first place?
Some classic examples of clean code heuristics are :
- Writing files with no more than
- One File per Class
- Don’t Repeat Yourself
- Build components that are self contained & independent
I recently had a debate with a friend who disagreed with these principles. It made me question the nature of these heuristics, and why they even exist in the first place. After working in the industry for a while now, I have a feel for why these conventions exist.
Reason 1: It is much more efficient to tell someone what to do, than to have them go figure it out
It’s virtually useless to tell someone to “go and write clean code”. A sensible response to such a demand would be “What exactly do you mean by that?”. To aim for clean code is to aim for an abstract concept. These heuristics ground that aim in actionable tasks.
Take this for example — How can a file be cleaned? We can start by checking a couple of things:
- is it a large file?
- are these methods too alike?
- is the language being used idiomatically?
Addressing these concerns will slowly chip away at complexity, and in their sum can tend to result in clean enough code. By following these simple rules of thumb, your code will on average be considered “clean” by some!
Reason 2: Reading complex code is mentally tolling
Complexity is reviled. Ask any developer, “ Would you rather work on a legacy spaghetti monolith, or a well oiled project? “. None will opt for the spaghetti monolith, because the well oiled project is easier to work with.
I’ve spent my fair share of time treading through the muck of legacy spaghetti code. Many of the issues I’ve come across can be addressed by a couple of these heuristics. DRY and Separations of Concerns alone would have saved me well over half of the headaches I’ve endured.
In summary, these heuristics exist to serve at least two purposes :
- Help developers write clean code via simple, actionable observations
- Minimize the amount of complex code in the world
These heuristics are guide rails when looking to reduce the complexity of your software. Determining the right combination and timing of these tricks is part of the essential trade of the software engineer. Please don’t ignore them — they make everyones life easier.