6 tips to write clean code

December 23, 2017

When it comes to writing code,
an ounce of prevention is worth a pound of cure
.
A professional programmer spends only 20-30% of the time coding, rest 70-80% of the time is spent in scrolling the existing code up/down, or navigating to other code blocks to understand them. The later percentage can also increase too much if the code is a big mess. 
But consider if the code quality is good enough that you do not need to navigate much understanding the code and also, the time for actual coding is the same, so the overall time reduces by a big difference of 20-40%.
So the question, how to write a code that is clean and easy to understand?
Here are some of the ways to write clean code:

1. Remember, you are the one who would be responsible for your code
Anyone can blame you for the code you write. In programming profession, sometimes there are cases when do not have ample time to complete the task, due to any reason, then you compromise on the code quality. This should not be done at all. A doctor will not say, I have to go home earlier so I will not be able to complete the full operation. So, remember, just to take the task with required dedicated time, or do not pick the task.


2. Use meaningful names for variables, classes, and methods
Avoid using names like temp, d, data, compute() etc. that does not denotes the intent of the code. Instead, use names that sound meaningful when pronounced.
For example,
"d" is a really bad variable name representing number of days
use names like "elapsedTimeInDays"

similarly, a method with name compute(int x, int y) does not denote how these values will be computed,

instead use a method name like add(int x, int y) that denotes the clear intent of the code.


3. Keeping the methods short that they fit on screen
Keep the method line count so less that it should be visible on your screen without scrolling up or down. Ideally, a method should not be less than 50 lines of code, and if your code exceeds that benchmark, just split it into two or more methods.


4. Do not use comments often
Comments are a way to express the failure that you were not able to write code that explains itself what it does. Moreover, it also happens that a piece of code is changed but the comments are not changed. In such cases, comments lie about what code does. Try to write code that expresses itself what it does and how.


5. Always follow the Boy-Scout rule
The boy-scout rule says that leave the ground cleaner than you found it. Use the same practice in coding. Try refactoring some extra code(maybe just a few lines), but cleaner than before. Eventually, the code will keep clean day by day.


6. Follow the Single Responsibility Principle
Just because you can, doesn't mean you should.
(Image source: Google)

Instead of giving many responsibilities to a single method, divide them among methods such that each method does one thing, but it does that perfectly.

You Might Also Like

0 comments