DEV Community


Basics of refactoring a bad code | part 1 - If condition

immathanr profile image Mathan raj ・Updated on ・2 min read

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 statement

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.

  • Readable
  • Concise
  • 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 relevant conditions

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.

Inversion of 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


Failing-fast will help you deal with fewer problems going further. (short-circuiting is the trump card remember)

We have discussed some of the practices I follow when I write

Tips: switch statements can be of a good replacement for if statement in case of checking for enum or strings.

Discussion (0)

Forem Open with the Forem app