Home > database >  Design pattern for if-else with common logic within the conditionals
Design pattern for if-else with common logic within the conditionals

Time:10-08

I have to implement a solution where the code behaves differently according to a different condition.

For example:

if(condition) {
   //create one object
} else {
   //create another object
}
oneCommonMethod();
if(condition) {
   //do one thing
} else {
   //do another thing
}
anotherCommonMethod();

Even the code inside the conditions is shared sometimes, it's just slightly variations of it. What would be the best approach here? What would be the best Design Pattern?

CodePudding user response:

You might be looking for the Strategy Pattern for the do something aspect. For the create an object aspect you could see if any of the creational patterns such factory or factoryMethod suits your usecase.

Different strategies can call into shared methods when required

CodePudding user response:

It is more efficient to have one "if-else" statement – whenever you can achieve the same goal with just one, there's no need to do an extra one and negatively affect performance.

In your code, given that the 'condition' is shared amongst both "if" statements (1), and given that the two "if" statements are at the same place in the program (2), it is better to merge the two "if" statments like this:

if(condition) {
   //create one object
   oneCommonMethod();
   //do one thing
   anotherCommonMethod();
} else {
   //create another object
   oneCommonMethod();
   //do another thing
   anotherCommonMethod();
}

This code achieves exactly the same goal as yours, except it's more effecient with just one "if" statement.

  • Related