Tips to write Clean Code
Why clean code matter and few tips to keep your code clean
Hello…
If you are not interested in my Chit Chat please skip to Introduction
.
It’s been a while since i wrote my last blog. During this time i read a book that i really loved. I thought i will share my notes that i took while reading the book or few highlights from this book.
Name of the book was Clean Code by Robert C Martin
while reading this book i highlighted few suggestions that i really loved. I thought it would be good idea to compile it in a form of Blog Post. If you find you can agree to most of these tips I will highly recommend you to read this book. I believe i should have read this book early in my career. Ok enough of chit chat let’s talk about the topic of this Post.
Introduction
This blog is about concepts that are basic concepts of software construction and will stay relevant despite the new technologies/frameworks come and go every year. Most of these concepts are language agnostic too. This post is about Clean Code. Few generic and proven ways to improve the quality of your code.
Let’s start with the question why quality code matters ?
If you have been a programmer for more than two or three years, you have probably been significantly slowed down by someone else’s messy code. If you have been a programmer for longer than two or three years, you have probably been slowed down by messy code. The degree of the slowdown can be significant. Over the span of a year or two, teams that were moving very fast at the beginning of a project can find themselves moving at a snail’s pace. Every change they make to the code breaks two or three other parts of the code. No change is trivial.
Bad code tempts the mess to grow. When other changes bad code they tend to make it worse. Dave Thomas and Andy Hunt
explained it very nicely with a metaphor of broken windows.
A building with Broken windows looks like nobody cares about it. So other people stop caring. They allow more windows to be broken. Eventually they actively break them. They despoil the facade with graffiti and allow garbage to collect. One broken window start the process toward Decay.
Tip 1 - Pick One word per abstract concept.
This tip is about naming things while writing code. Naming things properly goes a long way in writing clean code.
Pick one word for one abstract concept and stick with it. For instance it’s confusing to have fetch
, retrieve
and get
as equivalent method of different classes. How do you remember which method name goes with which class? If decide to go with fetch
use it uniformly across your codebase for same abstract concept.
Lot of people including me are not that great at naming things. So far i believed it’s fine it’s something i can live without. But recently read a quote that i could not disagree with :)
You know you are working on clean code when each routine turns out to be pretty much what you expected.
It is only achievable if we acknowledge the importance of naming things correctly. Then you can pretty much tells what piece of code does by just reading the function name. I am working now on getting better at naming things.
Tip 2 - Functions Should Do only one thing
I read this tip about clean code many times in different blogs and books. But never understood what exact does it mean. One boolean check count as one thing. One variable assignment count as one thing if that’s correct then i may end up writing thousands functions to do simple things. But after reading the explanation by Robert C Martin
my understanding got way better.
Author explained it using Step Down Rule:
We want the code to read like a top-down narrative.5 We want every function to be followed by those at the next level of abstraction so that we can read the program, descending one level of abstraction at a time as we read down the list of functions.
Let’s we are trying to write a testing framework for Web Based applications. Imagine there is a function that render a page Html in a string. This method check if the The page is test page then first perform the Setups and Then Add Page Content then add Teardown. If we want to requirements for this functions and try to write them as bunch of TO
paragraphs each paragraph represent a level of abstraction and subsequent paragraph represent the next level down abstraction.
As you can see how with each paragraph we go to a deeper level of abstraction. As one box in the above diagram represent one level of abstraction so each of these statements should be extracted as functions.
It turns out to be very difficult for programmers to learn to follow this rule and functions that stay at a single level of abstraction. But learning this trick is also very important. It is the key to keeping functions short and making sure they do “one thing.” Making the code read like a top-down set of TO paragraphs is an effective technique for keeping the abstraction level consistent.
Tip 3 - Command Query Separation for Functions
Functions should either do something or answer something, but not both. Either your function should change the state of an object, or it should return some information about that object. Doing both often leads to confusion.
Let’s have a look at an example to support this statement.
public boolean set(String attribute, String value);
This function sets the value of a named attribute and returns true if it is successful and false if no such attribute exists. This leads to odd statements like this:
if (set("username", "unclebob"))...
Imagine this from the point of view of the reader. What does it mean? Is it asking whether the “username” attribute was previously set to “unclebob”? Or is it asking whether the “username” attribute was successfully set to “unclebob”? It’s hard to infer the meaning from the call because it’s not clear whether the word “set” is a verb or an adjective.
One way to clean this up will be to separate the Command and Query part of the function into two different functions and result code should look like
if (attributeExists("username")) {
setAttribute("username", "unclebob");
...
}
Tip 4 - Clean Boundaries
Almost every enterprise project had 3rd party dependencies. Either it’s a reference to some NUGET package or NPM package. When we use code that is out of our control, special care must be taken. We should avoid letting too much of our code know about the third-party particulars.
We may wrap them with our code that hides or encapsulate the Third Part Interfaces
, or we may use an ADAPTER
to convert from our perfect interface to the provided interface. Either way our code speaks to us better, promotes internally consistent usage across the boundary, and has fewer maintenance points when the third-party code changes.
Tip 5 - Avoid Quick And Dirty Unit Tests
Author of book mentions a story about a team. But keep in mind that this story is not hypothetical. It’s actually a story from a real team
Team decided that their test code should not be maintained to the same standards of quality as their production code. They gave each other license to break the rules in their unit tests. “Quick and dirty” was the watchword. Their variables did not have to be well named, their test functions did not need to be short and descriptive. Their test code did not need to be well designed and thoughtfully partitioned.
What this team did not realize was that having dirty tests is equivalent to, if not worse than, having no tests. The problem is that tests must change as the production code evolves. The dirtier the tests, the harder they are to change. The more tangled the test code, the more likely it is that you will spend more time cramming new tests into the suite than it takes to write the new production code. As you modify the production code, old tests start to fail, and the mess in the test code makes it hard to get those tests to pass again. So the tests become viewed as an ever-increasing liability. Test code is just as important as production code. It is not a second-class citizen.
Test code does not need to be as efficient as production code.
See you
This post was my about my favorite things that i noted down while reading book. There are more things that i would like to share but may be in another post the things i loved about this book.
There was a part of book about Concurrency
that i found really insightful may be in my next post i will share those concepts about concurrency. It’s time for me to say goodbye will see you soon with some other post. Enjoy your life and Be humble. I will see you soon with new post.