1

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

I created some pseudocode to show it:

public void generalMethod() {

    firstMethod();
    secondMethod();
    commonMethod();
}

public void firstMethod(){
    if (condition1){
        condition1Method();
    } else {
        if (condition2){
            condition2Method();
        } else {
            defaultMethod();
        }
        condition2AndDefaultCommonMethod();
    }
}

public void secondMethod(){
    if (condition2 && condition1){
        condition1Condition2Method();
    } else if(condition2) {
        condition2Method();
    } else {
        condition1AndDefaultCommonMethod();
    }
}

I decided to use Template Method design pattern for it, because some code is common but some of them varies depending on conditions. Is it the right choice? UML diagram

I created this small UML diagram for it, but I have a problem, because Condition2Template and DefaultTemplate would share a common method which is not used by Condition1Template or Condition1Condition2Template, so I don't think I should add it to the abstract class Template. Also, Condition1Template and DefaultTemplate share a common method too. Could you please advise on this?

  • How are you going to implement this? As it is, it sounds like you will use static methods to access the funcionalities. That is, to run `condition1Method`, you would call `Condition1#condition1Method`, but for `condition2AndDefaultCommonMethod` which would you call? `Condition2#condition2AndDefaultCommonMethod` or `Default#condition2AndDefaultCommonMethod`? – Jetto Martínez Oct 10 '22 at 17:50
  • I will instantiate the corresponding Template class, then call `generalMethod` and then this method will call its corresponding `firstMethod` and `secondMethod` – Jose Robles Villares Oct 11 '22 at 08:58
  • Looking back at it, I might be confused by your namings. I was half-thinking that `condition2AndDefaultCommonMethod` were in `Condition2Template` and `DefaultTemplate`, but that wouldn't make sense if those calls will be done within subclases of `Template`. The `condition1` and `condition2` within `Template` are not referencing `Condition2Template` and `Condition1Template`, right? In other words, for `firstMethod`, you won't instantiate neither of `Condition1Template`, `Condition2Template` nor `DefaultTemplate` inside said method, correct? – Jetto Martínez Oct 11 '22 at 16:08

0 Answers0