We have all been in a situation that when we are growing as a developer often we find ourselves writing code that doesn't look right or we have a doubt that whether it follows the best practices. This article is just part 1 of the total n series. (I really don't know how many would come 🤷♂️)
If statements can be a root cause of writing bad code. Always think twice before writing nested if conditions whether there is a way to simplify it. A badly written
if condition can reduce the readability of the program.
Let's make the following assumptions here. Any clean code will have the following properties.
- Scalable - Should be able to allow more conditions or business logic to be added without affecting the above two factors.
Example 1 of Bad code
Improvement 1 - Combining relevant conditions
Improvement 2 - Applying inversion of condition
Combining multiple conditions that are relevant by using the logical operator can reduce down the lines of code and implies a better understanding of the condition.
Just by inverting the thought process that goes for the condition in if statement can vastly improve the readability.
Example 2 of Bad code
Improved Code - Applied short-circuiting + inversion of condition
We have discussed some of the practices I follow when I write
switch statements can be of a good replacement for if statement in case of checking for enum or strings.