How to Reduce Repeated If/Else Logic in Code
Where you have repeated code, there are a number of ways of avoiding the repetition that all amount to extracting the common part and still allowing the varying part to vary. See e.g. Avoiding Repetition.
Little is unique to Apex - it is more about these language independent design ideas:
- language mechanisms such as Replace Conditional with Polymorphism
- refactorings such as Extract Method
- design patterns such as Template Method.
Sometimes a small amount of repetition is preferable to introducing complexity. I like this quote from Code Reuse is Not a Good Goal:
Avoiding duplication is a critically important goal in software development, often saving you from outsized technical debt. But avoiding speculative complexity and abstraction actually has the same risk profile. You need to walk a fine line in the middle.
Some further reading:
- The DRY obsession
- Refactorings
- Catalog of Design Patterns
A good design patterns is only what you need to avoid code repetitiveness/boiler plate code. There is a nice blog which beautifully describes Visitor design pattern. You could try to implement this. This will help you solve the ugliness of too much if-else statements. Examples in this blog are not related to apex but they can be implemented in apex easily.
Salesforce has delivered idea Add "Switch" or "Case" Statement to Apex in summer 18 release. Now instead of writing nested if-else you can write switch statements which are better in terms of performance and code organization. Switch statements are better alternatives in some cases so you can give them a try as well.
The syntax is:
switch on expression {
when value1 { // when block 1
// code block 1
}
when value2 { // when block 2
// code block 2
}
when value3 { // when block 3
// code block 3
}
when else { // when else block, optional
// code block 4
}
}