How is it better to replace Else statements and how to do it?
Else is a decision that splits code in 2 pieces, opens up for 2 paths. When you add more than 1 decision, either at the same level or further down (nesting), then the paths are multiplied and this type of code is usually harder to understand and maintain.
Why? Well, to me this is because logic, as conceived and implemented by a developer, is usually different than that of the next person who interacts with it.
So why not make it easier to understand?
How? Basically 2 recommendations that sum up different approaches. Not exclusive, other practices could be applied to improve.
- Guard clauses Create statements that exit the current flow of code when required and prevent the rest to be executed.
- Refactoring to smaller pieces of code Reduce code complexity by creating small functions that are easy to understand.
References:
Top comments (0)