Clean code is a great book that revolutionized the way I coded. Written by Robert C. Martin it contains many gems about software development. Check it out on amazon here when you get a chance. I can still remember those days when I made quick and dirty solutions. Naturally when it came time to update my dirty solutions I would cry aloud. Imagine if I didn’t want to go back to my mess much less for another programmer. However when I changed my programming style to clean coding (cleaner 🙂 ) I laughed (in my head of course) at having to do updates. I said “they have no idea how easy it is to implement that”. I could laugh like that because I took the time to code better, more well thought out solutions. So now I felt sorry for future programmers in another way because they will have to understand that kind of coding style. Since they might probably be accustoming to having everything they need right in front them.
This article is a very short review of some of the more practical things I learnt while reading Clean Code. There is really so much more but they aren’t always universally applicable. A lot of the gems are very specific. Applying them unnecessarily will lead to over engineering your code base which is another sin in and of itself.
Slow down to speed up.
True professionals know that the second part of the conundrum is wrong. You will notClean Code : Chapter 1
make the deadline by making the mess. Indeed, the mess will slow you down instantly, and
will force you to miss the deadline. The only way to make the deadline—the only way to
go fast—is to keep the code as clean as possible at all times.
In my earlier days I would rush to complete tasks as fast as possible. It was a race to complete anything that was given to me. Granted there is nothing necessarily wrong with that ( of course there is 🙂 ) but it did mean that a lot of the things I built were really first drafts. By the time I presented the code I could already see how things could have been a little better. Often if it was a bug fix or a feature it would be a work around. The simplest way to do something. This meant that when that particular bug or feature (whats the difference 🙂 ) needed an upgrade I now had to figure out how to upgrade my work around. The pain was so real I would complain to management on having to make these updates. Slowing down solved this problem quite easily. I would listen to requirements, spend some time thinking on the best way to solve the problem and then I would implement the code as required. Note when I say think I mean seriously think, not a five seconds ponder, more like a half-hour minimum brainstorm session with pen, paper and google for research. This resulted in better solutions that hit the mark they aimed for. They weren’t better than they needed to be but open for upgrades. Work became much easier then. Future upgrades were a breeze. My work went at a gradually pace. Not a marathon session every time something happens.
Small functions small fixes
The first rule of functions is that they should be small. The second rule of functions is thatClean Code : Chapter 3 – functions
they should be smaller than that. This is not an assertion that I can justify.
I swear you can stop here. This principle forces you to think before you code. Trying to implement this instantly structures your application in a readable, upgrade-able, unit testable fashion. This can be over done of course but top much of a good thing is never bad just unnecessary and unnecessary is better that confusing. Which by the way is what happens when to try to do 10 different things in one function. It can work, it will work but it’s a puppy poop to debug. Hard to understand. Harder to upgrade. In fact once you touch a huge function you have now introduced so much change to the system that ideally everything else needs to be tested because you’re not sure what has been affected by what you did.
So the principle seems simple and self explanatory lets try it out. Say we wanted to output the numbers 1 – 20 with commas after every number except the last. We could do the following.
def print_numbers(): for x in range(1, 21): if x != 20: print(x, ",") else: print(x)
Which is perfectly fine by the way. It does exactly what we want. But using the small functions principle we could do a little better. Lets separate the part that outputs the actually number to the console.
def print_numbers(): for x in range(1, 21): output(x) def output(number, stop=20): if number != stop: print(str(number) + ",") else: print(str(number))
Now we have two functions. We can reuse output elsewhere or we can redefine how it works. Maybe we want the output to be sent to a text file or log the results elsewhere. We can do all that without interfering with how the main function prints the numbers. We can even modify how the output function works. We can change the stop argument so that we can leave out the comma at other places. Which really does nothing of value but you get the point.
Don’t repeat yourself or at least try not to
Duplication may be the root of all evil in software. Many principles and practices haveClean Code – Chapter 3 – functions – pg 48
been created for the purpose of controlling or eliminating it.
DRY. Everyone know this one. But its not really followed all the time. I think the reason for this is that it is pretty difficult to truly implement. It requires more fore thought and experience. It requires understanding different patterns ideally or a more structured approach to programming in general. It still is a great principle to use whenever you can. Tools, plugins, frameworks and programming languages are all created using this so in theory whatever language you use will be doing this so don’t sweat it too much. Often times it might be easier to duplicate a function or class if you don’t fully understand what the original does quite. It means however you now have to maintain two code blocks of a similar nature.
Example time. Say we had a two get users functions that returned a user based on type and email.
def get_admin_user(): name ="admin" email = "email@example.com" model = findUserByNameAndEmail(name, email) return model def get_guest_user(): name ="guest" email = "firstname.lastname@example.org" model = findUserByNameAndEmail(name, email) return model
Nothing wrong with this we can get different kinds of users easily. But we can make it better
def get_user(name, email): model = findUserByNameAndEmail(name, email) return model
One function to rule them all. Now we can get users without repeating ourselves.
get_user("admin", "email@example.com") get_user("guest", "firstname.lastname@example.org")
I could be wrong but DRY will be done if you implement MSF aka Make Small Functions. Which is why I said it’s all you need.
Naming saves lives
The name of a variable, function, or class, should answer all the big questions. ItClean Code
should tell you why it exists, what it does, and how it is used. If a name requires a com-
ment, then the name does not reveal its intent.
This one is also common knowledge. Name everything in a sensible fashion. This is not only for your future self and the next programmer. Having proper names makes your code more readable and self documenting. If you’re not sure, that is something you want. This can be a bit hard to do sometimes. And the more functions you have the harder it is.
create_user_with_default_name() register_event_after_login() update_db_automatically() clean_old_records_from_current_db()
You can end up with some long names for your variables, functions and classes. But this hurts no one. So try it.
Clean code is a really great book. It comes with a lot of examples. I would suggest all programmers check out this book. It will enhance your programming knowledge and make you an all round better programmer.