Quick Tips for writing Clean Code Part-1

This blog aims on writing clean code and avoid some common mistakes that programmers usually make while writing code.

Good code is a code, which everyone (programmer) can understand easily and it should be self-explanatory.
 
As stated by Martin Fowler:
 
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
 
So, in the first part we will be discussing the below points: 
  • Why signal to noise ratio is important?
  • What is DRY principle?
  • Avoid being stringly typed
  • Avoid MAGIC Numbers. 
Let’s start discussing each one by one.
 
Why signal to noise ratio is important?
 
Signal-to-noise ratio is a measurement used in science and engineering that compares the level of a desired signal to the level of background noise.
 
In terms of programming CODE with high signal to noise ratio is easier to understand.
 
 
So, signal can be the logic that follows the TED (Terse, Expressive, Do one thing) rule.
 
Terse means your code should not be excessively wordy and we must refactor our code regularly to keep the mess as low as possible and to prevent it from getting huge over time.
 
And noise could be:
  • High cyclomatic complexity
  • Huge classes
  • Repetition
  • Poorly named structures
  • Unnecessary comments·
  • Zombie code and many other things 
What is DRY principle?
 
DRY stands for do not repeat yourself and it is one of the most fundamental principle that everyone should adhere to.
 
As Copy and paste is a very big design problem, so we should always try to follow DRY so that we can increase the signal to noise ratio.
 
We must not forget that every line of code is a liability to maintain.
 
Avoid being stringly typed.
 
We should avoid being stringly typed, as in the below example we can clearly see which is better.
 
So, idea is to create an ENUM as this has several benefits:
  • Strongly typed means there is no scope for typos means the chances of making mistakes gets reduced.
  • It gives intellisense support also as now you can see after typing EmployeeType what all other types of employee are present. 
Avoid MAGIC Numbers
 
The biggest benefit of removing magic numbers is that it clarifies intent.
 
We should use well named constant or enum and should not use magic numbers as they raise question i.e. why only this number.