11

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.

2 Answers 2

16

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:

4

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
    }
}
2
  • 3
    I still don't understand how switch case will solve code repetition problem in first place, its just beautiful way of writing if-else. Jun 17, 2018 at 12:00
  • @PranayJaiswal check my updated answer, now does it look relevant?
    – Mr.Frodo
    Jun 17, 2018 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.