How to Reduce Repeated If/Else Logic in Code

I’m relatively new to Apex, and one thing I’ve found is there are a few places in my code where the same the same if/else logic is repeated. I.e.

if (first_condition) {
    // do something
} else if (second_condition) {
    // do something else
} else {
    // do something different
}

Here, first_condition and second_condition are the same in multiple parts of code. I think I can use Apex Factories and Flows to remove the redundant code, but I’m really unsure how to use them.

Answer

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:

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:

Attribution
Source : Link , Question Author : Roshan Munjal , Answer Author : Keith C

Leave a Comment