Sweep, Sweep, Here Comes Clean Code!
Imagine this. You’re in a records store, and you’re looking for some vintage Earth, Wind, and Fire CDs. If the record store sorted and categorized their CDs, you will find your CDs faster. In addition, the neat interior design & architecture will make you feel at ease while you are searching for your CDs.
Just like the record store, you have to know how to write and organize your code neatly if you want to build something great. If someone else acquires your code and attempts to understand it, they only need to see the variable names or packages or classes until everything clicks into place. They don’t need to say “to hell with this” this code and start it again from zero.
This is where clean code comes in.
What is Clean Code you say?
So you see, it is merely not enough if you finish your development faster. If others cannot comprehend a single line of your code, it will only cause another tech debt.
Your code is classified as “clean” if it can be understood easily by everyone on the team. Clean code can also be read and enhanced by a developer other than its original author.
With understandability comes readability, changeability, extensibility, and maintainability.
— Do I have to care about it?
Duh, of course! One of the reasons why is your code will describe your thought process to others. That is why you have to start thinking about making your code more elegant, simple and readable.
Aside that, there also some really great benefits from clean code, such as:
1. Easier to Test
Messy, complex code is difficult to test. It isn’t just difficult to unit test, but it is hard to do any sort of automated testing if the underlying code is messy. Sure, it can theoretically be done, but cleaner code is usually easier to tes and–more to the point–easier to diagnose when something does break.
This particular point is very important for our team, as we implement TDD during the development process of PsychoTip. With clean code, the constant creation of test suites is not that much of a burden, and its easy for us to spot the find the source of failure in the case of failed test cases.
2. Lower Maintenance Burden
The vast majority of the cost of software is not in the initial construction: it is in the maintenance, with most of that maintenance involving activities other than directly fixing bugs. Over time, we might need to alter the existing code to adhere to new features, or merely just to improve the codebase.
With PsychoTip, we often revisit old codes to add modifications in order to make new features work. As we have a huge amount of tasks and literally no time to waste, we really need to re-grasp what the old code does in a snap.
3. Easier to Spot Bugs
If something breaks, it is much easier to identify the cause if the code is clean. When working with bad code, it can be such a torture to find out why a new part of code broke another part of code. With clean, well-defined code, this is not an issue.
Spotting bugs easily is something we always want to have during development. With our fast paced environment, we cannot tinker too long on the faulty code and keep guessing where the bug could be. We need to fix it quickly and move on to the new set of tasks.
4. Increased Code Communication
What good is code that only one person can understand? More often than not, multiple developers can end up working on one project, or a whole new team of developers will take on the project later. Even you might struggle to understand your own bad coding when you revisit it in five years’ time.
PsychoTip’s current development is limited to around 4 months, which is far too short to implement all the desired features of the app. With this, there is a high chance for PsychoTip to be picked up and improved by other developers in the future. As such, we always want to make it easy for them by writing clean code that is easy to understand and therefore not time consuming to edit.
5. Happiness
Speaking from personal experience during the development of PsychoTip, I can definitely say this: Developers working in a clean code base are going to enjoy it much more than developers working in a messy code base.
Just like a workstation, a clean and neat code will evoke a pleasant feeling within the programmer, hence reducing burn out. A code should always be written with a goal to minimize the amount of pain that the maintainers feel down the road.
So what exactly are the characteristics of Clean Code?
In short, the characteristics could be defined by this:
1. Elegant
Clean code is pleasing to read. Everytime you skim through it, it should make you smile and make you a little proud of yourself inside.
2. Readable
Clean code should read like well-written prose. If the naming conventions, spacing, structure, and flow used in a program are not designed with the reader in mind, then that reader will almost certainly fail to understand the original author’s intent.
3. Simple
Do one thing with the Single Responsibility Principle (SRP), which defines that every module, class, or function should have responsibility over a single part of the functionality provided by the software.
4. Testable
No one writes perfect, bug-free code on the first try. Writing clean code means writing tested code. That way, future users can be confident they’re interacting with something that works. Moreover, when making changes, they will have a ready-made test suite to confirm that nothing broke.
And now, we move on to the fun part. Implementation.
Implementing Clean Code #1 — Meaningful Names
First, let’s talk about names. Everything in an application has a name.They communicate what your code wants to do to the developers who read your code. Choosing good names to use makes your code seems like a piece of cake to read for other developers, as well as yourself in the future.
Some key points on making meaningful names:
Use intention-revealing Names
Choose names that tell you why it exists, what it does, and how it is used.
Use Pronounceable Names
Humans are good at words and words are, by definition, pronounceable. If you can’t pronounce it, you can’t discuss it without sounding like an idiot. This matters because programming is a social activity.
Class Names
Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. A class name should not be a verb.
Method Names
Methods should have a verb or verb phrase names.
Pick One Word per Concept
One and the same concept in your application should have the same name. Using the same word per concept will help developers more easy to understand the code.
Let’s look at an example for this part shall we? Here I have PsychologistDashboard.java, which has a purpose to create the dashboard page for psychologists.
We can see the names that are used to describe the variables and functions reflects its purpose, such as the logoutButton, where it contains the — you guessed it — logout button from the xml file. All the names used are also easily pronounced, no keyboard-smushed words.
The class name used — PsychologistDashboard — is a noun, and all the methods inside the class are begun with verbs, such as onBackPressed.
The “pick one word per concept” criteria is also fulfilled, with onCreate and onBackPressed using the same verb for similar actions. A more clear example can be seen on this snippet from ClientRegistrationPage1.java
Here we see that three of these error handling methods use the same verb to define their similar actions, “show”. There are no usages of synonymous words such as “display”, “reveal”, etc.
Implementing Clean Code #2 — Functions
How do you make a function communicate its intent? There are some best practices help you write good functions easy to read and change.
Small
The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that.
Do One Thing
Functions should only do one thing and do it well.
Function Arguments
Functions should have < 3 arguments.
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible.
Another example from our project that we can see for this part is this method from our admin-side application, which is developed with Python.
This function is considerably small, consisting of 5 lines with not more than 80 characters per line. The function does only one thing, which is to pass the list of quote objects to the html file. The function is monadic, in which it contains one argument which is “request”.
Implementing Clean Code #3 — Comments
One word, avoid. If you see a bad code somewhere, don’t comment it. Simply rewrite it. Comments are also very easy to be abused and used out of context. Case on point:
/*
This code sucks, you know it and I know it.
Move on and call me an idiot later.
*/
Throughout our project, we always aim to not use comments on production code. If we do come across a method that needs further clarification, we try to simplify it.
Implementing Clean Code #4 — Unit Tests
Test code is just as important as production code. The Test Driven Development (TDD) is a software development process that relies on the repetition of a very short development cycle: requirements are turned into very specific test cases, then the software is improved to pass the new tests, only.
As explained in my previous post, we do implement TDD throughout the whole project so we got that covered.
Implementing Clean Code #5 — No Pressure
Last but not least, relax. It’s easy to get caught up in the world of clean code and want to absorb everything once in a day. The tough news is: it takes time, months, years and dedication. The principles must be learned and practiced but it all starts with a decision to make everything cleaner, onwards.
So there you have it, all the fundamentals of clean code and how we used it throughout the development of PsychoTip. If you want to know more about Clean Code and dig deeper, I suggest reading the book Clean Code from Robert C. Martin(Uncle Bob).
See ya in the next issue!