Home > Blockchain >  How can abstract my code to avoid duplication if a increase the number of variables to consider?
How can abstract my code to avoid duplication if a increase the number of variables to consider?

Time:12-24

Currently there are be 4 combinations

  • Add hours.
  • Add days.
  • Subtract hours.
  • Subtract days.
private String modifyDate(Character symbol, LocalDateTime date, Long digits, String period) {
        switch (symbol) {
            case ' ':
                if (period.contains("days")) {
                    return date.plusDays(digits).toString();
                } else {
                    return date.plusHours(digits).toString();
                }
            case '-':
                if (period.contains("days")) {
                    return date.minusDays(digits).toString();
                } else {
                    return date.minusHours(digits).toString();
                }
            default:
                System.out.println("Not defined operation");
        }

        return "";
    }

If a new period is added (let's say years), it will be necessary to add a new if statement in each case:

if (period.contains("years")) {
    return date.plusYears(digits).toString();
} else if (period.contains("days")) {
    return date.plusDays(digits).toString();
} else {
    return date.plusHours(digits).toString();
}

Also if a new unexpected case is added (a combination, especial cases), then it will be necessary to repeat the logic to validate the periods.

Do you have a recommendation to improve the solution? Pattern recommendation, functional interfaces implementation, any recommendation is welcome.

Thanks in advance!

CodePudding user response:

The general recommendation by Martin Fowler is to Replace Conditional with Polymorphism.

https://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html

In terms of design patterns, this would often be the Strategy Pattern Replace Conditional Logic with Strategy.

https://www.industriallogic.com/xp/refactoring/conditionalWithStrategy.html

If you have a small, finite set of conditions, I recommend using an enum to implement the Strategy Pattern (provide an abstract method in the enum and override it for each constant).

I hope it might be helpful for you.

CodePudding user response:

This is solvable through a Strategy Pattern in combination with an Enum.

https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm

  • Related