Take Away from clean code
I recently went through my code when our client asked for an update but when I saw the code I had written 2 years ago I was shocked. I decided to improve coding quality and read the book ‘Clean Code’ by Robert C. Martin, well known as Uncle Bob. These are some of the takeaways I got from the book.
1 Boy Scout Rule:
The Boy Scouts have a rule: “Always leave the campground cleaner than you found it”. This can apply to our code base also. Try to improve the quality of code a little bit over time. The entire code base becomes a good one.
2 Relation between naming and Scope:
2.1 Variable name and scope: Length of variable name and scope has linear relationship. If the scope of the variable is more then length of the variable is preferably more and vice versa.
2.2 Class name and function name: Length of class name and function name has inverse relationship with scope. If the scope of the class is more, then name is preferably less and vice versa
3 One word per concept:
Try to associate a word with concept and stick to it. We can interchangeably use get and fetch. If we associate one word for a concept and stick to it we can easily go to the entire database. E.g., if we set fetch for fetching from the database, all the databases related must start with fetch. Then it is easy for us to understand the code. Every time we see a fetch then definitely we can make sure that it is a database call
4 Try not to repeat class name inside members:
Consider the example:
Second case is better to read
5 Split the function to multiple function if there is branching:
if user_type == “type 1”:
## code block 1
elif user_type == “type 2”:
## code block 2
## code block 1def send_type2_notification():
## code block 2
If we use the approach 2 the code if more readable and code is very compact
6 Don’t use the third party code directly in code:
If we are using any third party code, make sure that it must be wrapped with another function so that in the future if we want to change to another tool it is very easy for us to change the code.
Consider that we are using a third party called abc and method aaa
Directly using code
In future if we are planning to change abc to xyz then we have to update Function1 and function2
Here we need to only update wrapper_function and can be tested separately
7 Commenting the code:
Related to the comment he says don’t comment the code unnecessarily. Each unwanted comment is an inability of a programmer to express the code efficiently. Some of the places we need to comment the code are:
2 Warning and Todo comments
3 JavaDoc for external APIs
8 Always follow a team rule:
Each and everyone in the team should follow the rule properly.
Other than this one thing we can do is stay updated with our technology we are working on and follow the best practices for that technology.