vendredi 24 décembre 2021

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

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!

Aucun commentaire:

Enregistrer un commentaire