Clean Code —A Lesson in Loving Oneself
Or alternatively, why writing in cursive fell out of fashion in the first place
I’m sure all of you have been pestered about reading what some people call the software engineering bible, Clean Code by Robert C. Martin. But this is the digital age, why would you ever read a book about some boring thing called clean code? Your code is clean enough anyway.
Well, the answer is simple, because there’s real benefit to it. But there’s benefit in everything, do you really have to apply it? What is it anyway and why is it thrown around so much in this world. Well, to start with, we have to start at the basics.
Once Upon A Time…
So this is a classic story. Picture this, you just made an app that got number 1 ranking in the AppStore after first week of release. Suddenly a lot of bug reports starts coming in of what users have experienced. But there’s just one problem, your app was so massive that you don’t know where the bugs are.
As you keep searching and searching, days pass and your users grew even weary. You tell them you’ll fix the bugs today, yet you struggle to find your way across your jungle of a code. Eventually you succeed, you cry out, “I did it, everyone, I fixed the bugs!”, but there was no response. Your users left long ago.
So what was the point of that story? The point is that an unclean code isn’t bad now, but later. It’s like how an unclean room invites germs which can bring you disease. The bad thing about a bad code is that it can snowball out of control really easily.
But of course, why should you care now? Your application won’t get used in the future anyway. I used to believe that, until I actually want to make another game using Godot and needed to look at how I did some of the character movements. What I found was horrendous.
I coded this not 6 months ago, and I think I need a day to fully process what this does. And the badness doesn’t stop there, the code itself is almost 1000 lines long. Imagine how much time you have to spend trying to understand the code to replicate it on your future works. It may just be better to write it from scratch!
Now, we know what happens if a code is bad, but how do you make a code clean? What is considered clean?
What is Clean Code?
Like all things programming, clean code has no true definition. Instead, it’s a set of guidelines that you can follow to attempt at minimizing the bad in your code. A clean code is:
- Easy to read and understand.
- Straightforward and doesn’t repeat itself.
- Easy to change yet doesn’t require any change.
- Focused and modular.
- And most importantly, looks good enough to be put on stack overflow without being booed.
While that last point might be a joke of mine, it is one of my basic consideration when thinking if a code is clean or not. If you are sure that in the next year you can look at a your code the same way you did right now, that’s a clean enough code.
Now I did say guidelines, and there are a lot of stuff. I may miss some stuff along the way, but to make sure you get the full experience, go read this later.
Clean Code: How to Use It
General
This part is the boring part. Basically, you need to follow conventions, keep your code simple, always clean stuff, and avoid duplication. In practice, you probably won’t remember these much if at all. So for general stuff, I advise you to do a double check after every session of coding or to let a tool like linter do stuff for you.
Sometimes, you don’t think much about copy pasting your code as it’s a simple validation check that you did on another file. But it’s actually not good to keep doing this as you may need to repeat it more and more times. A tool to automatically check your code is important, something that I may cover on my CI article!
Naming
This is arguably the hardest part of clean code. Not because it’s hard to name things, but because it’s easy to name things the wrong way without ever realizing. Take a look at my previous mistakes.
I certainly thought my naming was right, camelCase is standard in programming, right!? Now if you actually follow the general part, you have to follow conventions, and in python snake_case is the convention… Because a python is a snake…
Okay, jokes aside, as you can see it’s really easy to screw up naming things even if you think it’s good. But what do you actually need to follow? Well, they are:
- Make them pronounceable and searchable
- Make them descriptive and meaningful
- Make them consistent according to their context
- Make them easy to remember
- Avoid encodings such as their type
An example of the last one would be doing this in my project:
Instead, you could do:
Simple, but really hard to accomplish at the first try. Machines cannot catch some of these, so it’s up to you to review your code!
Comments
This is debatably a controversial topic for me, because to our team, comments are what makes our code dirty. While that is true for bad comments, a good comment can save you a day’s worth of googling. As a rule of thumb, if the code is simple and clear enough, which it should be if you follow the other principles here, you don’t need comments.
Comments are hard to maintain, hard to write, and when it is easy to write, it’s most likely redundant information. Comments should only be there to clarify something. Here are some examples on our project:
The top one is a bad comment, it only repeats itself on a class that doesn’t need any comments in the first place. The bottom one is only a decent comment, but they only need clarifying because the underlying implementation was bad. So if you follow a lot of these guidelines, you shouldn’t need them at all.
Functions
Another important aspect in clean code. The thing to look out for in a function is mostly that it must be small, modular, and single responsibility. Remember our friend the Godot game? Well let’s take a look at it again.
This function basically violates every single principle of a good function. It is not short, not modular, not everything! So then what is a good function? An example in our project would probably be:
Not very interesting, I know. But this serves as a baseline of what a function should be like and what it should do. It’s modular, it does one thing, and it’s short. It’s fairly hard to write all functions like this though, my suggestion is to have one function as a pivot and have your other functions copy that one function’s style.
Quickfire Round
There are so much stuff to explain in clean code that this article cannot hold them all. So we’re glossing over some of them in this small section!
Design rules! Have variables be at their respective locations, follow the Law of Demeter, and have stuff decoupled to avoid over dependency.
Classes! Just like functions, these should be small, single responsibilities, and don’t have overarching package levels. Objects and data structures should be internal, hidden, and only call functions that they have or they know.
Formatting! Don’t have lines going too long, basically.
Tests and Exceptions
And finally, we have arrived at the last section. I chose to combine these two because they’re closely related. So as I previously have covered on TDD, unit test helps with making your codes better. One of clean code’s main point is to use TDD, but what are the other points that a test should have?
A test should be independent, repeatable, and test only one thing. There are some that say that tests should be fast and that you shouldn’t be afraid of making the test fail after you cover everything, but to me, they’re wrong. A test should be a double check, making sure you didn’t miss anything, but you shouldn’t rely overly on tests. Here is an example of a good test:
Simple, short, and sweet. But how is a bad one? Here’s an example from my old project:
Here you can see that it tests for two models at once, something you should never do, because if it fails, you don’t know which one until you read the logs!
To tie in with tests, you could use exceptions to manage tests. Now why use exceptions? Exceptions are great to provide context in case something fails. Rather than having status codes you can have meaningful exceptions to tell you exactly where it fails. You can use exceptions as a mean to test your codes! For example:
This test utilizes if the function invoked raises an exception or not, pretty neat and it makes you able to not write negative tests for it.
Investing in Clean Code
Clean code is not like the other abstract things in programming. Its benefit are not visible now, heck, you may never even see it. But it’s an investment, it’s not for current you, it’s for the future you.
The way we have implemented clean code on our codes was not out of duty, but out of necessity. You see, this is the third time we have written a Django application for a project. And this project relies heavily on our previous codebases, one that was built upon the bases of clean code and one that was not.
It would be fun to try and post it as a story, but reading that might be a pain so here are some direct benefit we feel:
- High reusability of pristine code. This is my main argument on why you should do clean code. Not just because it’s readable and maintainable, but it’s reusable. In future projects, you can copy and paste your code, knowing that it is the best, and the cycle would continue. Having a huge codebase of good tools is the only thing you need, honestly.
- Faster team communication. Your codes aren’t only for you, it’s for other people too, people that work with you. We found that we communicate faster when the code is clean. Well that’s a given, but how so you may ask? Well, I was doing a one-two punch with my friend, with me making the CU aspect of a model and my friend making the RD aspect. The process is streamlined from Read first, to create, to update, to delete, but the task division means we have to work in tandem. Clean code made us done in one day.
- Higher spirits while coding. Yes, a purely psychological effect in the list of benefits, how wonderful. You see, whenever someone write an idiotic piece of code, we would always go on discord and rant about it. It brings the mood of everyone down. With clean code however, we don’t need to do that anymore, because everyone write good stuff… Well, at least we don’t do it as much anymore.
So, you skipped to the end, huh? Make sure to read at least the references I gave, they’re probably a lot more helpful than this. But let me summarize this article for you then.
If you love yourself, and love others, you should apply clean code. If Gandhi knew about clean code, I’m sure he’ll advocate it as it can bring world peace. So let’s get stronger with clean code, more than today, more than ever.
References:
https://medium.com/swlh/what-is-clean-code-463d25fa6e0b
https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29