Read time: 6 minutes
1. What is Clean Code and why is it important?
If you work in software development, this scenario might seem familiar: It’s the end of the day, you just finished your fourth cup of coffee, you run your project. “It works!, you say with a slightly trembling voice. A sentiment of relief engulfs you as you push the last changes to the repository. You come in the next day and you’re called in for a code review.
You open the source files and your colleague’s face turns red in anger and confusion as your code seems like hieroglyphs to him. Before you know it you’re back to square one, trying to rewrite that which you just spent a day or more doing. Moral of the story? Clean code saves time and high blood pressure levels.
On a more serious note, we are programmers. We painstakingly learned the intricacies of one or more programming languages and more importantly learned how to express our intent using those languages’ structures. But, we want to become better. We want to be like those programming wizards; able to write elegant solutions to every problem that we encounter. Cleaner written code can help us achieve that.
“So, what is clean code?” Basically, it boils down to these rules. The clean code must be:
-
Readable and well structured;
-
Extensible;
-
Testable.
You might be thinking right now: “But code that does its job should be good enough, right?”. Well, no! Your code might be functional, but it is useless if you can’t build on top of it.
In the preface of “Clean Code, A Handbook of Agile Software Craftsmanship” (the book that this article is based upon) by Robert C. Martin, the author mentions this: “Even bad code can function. But if code isn't clean, it can bring a development organization to its knees.”
Then he proceeds in telling the story of a company that eventually went bankrupt because the development team failed to maintain the codebase for their most important product. Bugs went unresolved from one release to another, load times got bigger and stability plummeted.
“How do I prevent this?” Learn how to write clean code! Keep in mind that it won’t be perfect the first time around. Programming is a craft. It takes time, dedication and multiple iterations to get things right. But, in the end, it will all be worth it.
2. General guidelines for writing Clean Code
Here are some general programming tips to get you on track with clean code writing:
-
Don’t write bad code (duh...). No one rushes you, your boss will not be angry if you stay a little longer to clean up and improve your work. As they say: “If something is worth doing, it’s worth doing great.”
-
Don’t postpone changes. “Later equals never”.
-
Previous messes will slow everyone down. The only way of going fast is to keep everything clean and organized.
-
Clean code comes with experience. Cleanliness is an acquired sense.
-
Apply the boy scout rule: “Leave the campground cleaner than you found it!”. Each of us has the responsibility to leave the code a little better than we found it.
Things to avoid:
-
Multiple languages in one source file: causes confusion and adds unnecessary complexity.
-
Duplication: respect the DRY principle (“Don’t Repeat Yourself”).
3. Clean Coding best practices
a. Naming conventions
Next, we’ll tackle naming conventions:
-
Give meaningful names. Names like “a”, “c” or “X” give the reader no real information about the reasoning behind using these objects.
-
Don’t be afraid to use lengthy titles for functions. In the long run, this will combat disinformation. (Am I using the right method? What does this function do exactly?)
-
When you take a step back and look at the entire class, it should read as close as possible to a natural language. Even an inexperienced developer should be able to understand what you just wrote.
b. Functions
Functions are the building blocks of every piece of software. How do we treat them?
-
Functions should always be small and should always do one particular thing and do it well.
-
Try to keep the number of functions to a minimum.
-
Function names should be descriptive of their intent. Use verbs like “write” and “sort” whenever possible. (ex. writeNameField, sortArray)
-
Refrain from writing functions with side effects. As stated previously, they should always do one thing and one thing only.
-
Functions will not come out perfectly the first time around. Improvements will be made as the development advances. (see “Successive Refinement” below
Things to avoid:
-
Output arguments: they are counterintuitive.
-
Dead functions: they should be refactored or deleted.
c. Comments
Comments are useful, but let’s see how we should go about using them:
-
Comments do not replace code. We should learn to express our intent using the available language structures.
-
Keep the comments short and concise.
-
Inappropriate information: reserve comments for technical notes about the code and design only; everything else is irrelevant.
-
Obsolete information: causes misdirection and misinformation.
-
Redundancy: refers to a comment attributed to something that describes itself.
-
Ambiguity: poor choice of words, incorrect grammar.
-
Commented code: should be removed or refactored. Adds unnecessary complexity and causes misguidance.
d. Formatting
Formatting is also important though often overlooked:
-
Source files, ideally, should be read as newspaper articles. A simple title that encompasses the source file content, followed by the high level concepts and algorithms and lastly the lowest level functions and details.
-
Pieces of code that depend on one another should be positioned close to each other.
-
Use indentation. It makes code readable to humans. (beep.. boop)
e. Classes
What’s next on the Clean Code menu? Classes.
Based on the standard Java convention, classes should be organized such as:
-
List of variables (beginning with public static constants, followed by private static variables and so on);
-
Public functions;
-
Private functions;
-
They should be small. Just like functions.
-
The Single Responsibility Principle: every module or class should have responsibility over a single part of the functionality provided by the software.
f. Successive refinement
And last, but not least, successive refinement:
-
To write clean code, you must write dirty code and then clean it. No one expects perfection on the first pass.
-
In the case of clean code, programming is more of a craft rather than a science.
-
Writing an extensive feature can be a daunting task to get right. After the functionality has been implemented, see if you can find ways to improve it.
-
Don’t be afraid to ask for a more educated opinion! That’s why seniors are there. It’s their job.
-
Be careful of massive changes because, more than often, programs don’t survive these “improvements”. These “improvements” should be divided into smaller pieces that can be applied without affecting the program structure irreparably.
4. Conclusion
In conclusion, there is a thing that should be mentioned. If your client implements a coding standard you should try to adhere to it as well. This helps in maintaining consistency across the entire codebase.
If you read this article it means that you have taken a few steps in becoming a better programmer. Who knows, maybe one day you’ll be a rockstar, or a ninja, or something even cooler.
References:
1. “Clean Code, A Handbook of Agile Software Craftsmanship”, Robert C. Martin, Prentice Hall