How to eliminate if-else chain, for long life software

Sameh Muhammed - Oct 10 '22 - - Dev Community

Motivation

All programing principles and paradigms aim to enhance code readability and maintainability, from OOP to functional, SOLID, DRY, YAGNI, KISS and design patterns all these main purpose is to write clean and maintainable code for long life software, as a software by nature will keep evolve and change, so all these concepts help us to make our software flexible and easy to change.

Boost readability and maintainability

One of most popular code smell is if-else chain or code branching, of course you can't develop a software without if-else but heavily using to harms your code and in order to eliminate/reduce multiple is-else chain there are some tactics you can do to avoid this code smell.

Fail early mechanism

This mechanism works by validate violation first and terminate if any violation happen, instead of checking for right values and terminate if not as below

Image description

Flat-Chain mechanism

This mechanism works by repeating your conditions over if statements to avoid branching in your code and this approach favoring readability over performance if code may be need a lot of changes in future

Image description

Use polymorphism

If you have multiple operations and you need to fire specific one depending on specific condition, you can encapsulate creation of these operations into one single class(Factory) and delegate the determination of what operations fit for this criteria to one isolated place and make your code more readable and this make code strict to open-closed principle.

Image description

Predicate-Action mechanism

You can apply this mechanism by using a Map or List of Pairs one side is a predicate(condition) and the other side is the action you want to fire if the predicate success and by iterating over this pairs you can achieve your conditional logic in better way

Image description

Use State design pattern

By using this you first define your states as below

Image description

Then implementing each state and which state currently now and which state you are allowing to return from current one.

Image description

Image description

Then use the states with your object

Image description

Demo project for all tactics

IF YOU LIKED THE POST, THEN YOU CAN BUY ME A COFFEE, THANKS IN ADVANCE.

Buy Me A Coffee

. . . . . . . . . . . . . . . . . . . . . . . . . . . .