What is clean coding?
First and foremost, what even is clean code? At its core, clean coding is writing code that is meant to be read by people. This is an important idea. If you take only one thing away from this post, it should be that when you write code your audience are the people who will read it in the future.
Why code cleanly?
The computer is much better at reading code than people are. As long as the code is syntactically correct and does what it’s meant to, there won’t be any problems on the computer’s end, but people have to read that code. If the code is essential to your business, it’ll be read repeatedly as your business adapts and evolves. If the code was haphazardly thrown together in a hurry, every person who goes to read the code is going to have to slowly muddle their way through it, and they may not even understand it when they go to change it! This wastes countless people’s time and introduces bugs. Code like that is high in technical debt. From wikipedia:
In short, technical debt is stuff that you should’ve done, but you either forgot to do or decided to do later*. Technical debt can and has killed companies. Clean coding is your front-line defense against technical debt. It won’t eliminate it, but it’ll help greatly.
How do I code cleanly?
There are many suggestions elaborated thoroughly and with plenty of examples in Robert C. Martin’s book Clean Code, so I’ll just give the abridged version.
Choose names carefully
Names should be descriptive. Variable names probably should be nouns. Function names should start with an action verb and be “unsurprising”. That is: if you see the function name “get_all_users”, when you read its implementation you won’t see anything that makes you double-take.
Obey the Single Responsibility Principle (SRP)
If you don’t know what that is (shame on you**), here’s wikipedia’s definition:
This extends to functions as well. They should be small and do one “thing”. Complex behavior should be composed out of simple parts.
Write clear, informative comments
Comments should be rare. Your code should speak for itself, except for when it can’t. That’s where comments come in. Your comments should clarify complex code and warn of dangers.
Format your code consistently
It doesn’t matter whether you prefer snake case to camel case or you like your opening braces on the same line as the function or on a new line. Be consistent. Preferably, your entire codebase should be governed by the same style guide.
Wrap-Up
Those are the most important suggestions. The only one that doesn’t directly relate to making the code easier to read for humans is obeying the single responsibility principle, and a major effect of the SRP is shorter functions and classes. Remember: your audience when coding is the people who will read the code in the future!
* Later almost always means never.
** More on the amazing value of the SRP can be found in the article “KISSing SOLID Goodbye” in Overload 122.