samedi 13 août 2022

Choosing right design pattern

I have been contemplating for quite a while what would be the best design pattern to refactor given code to, but every time I think I have it, something just does not feel right.

public CalculatedCommission calculatedCommission(BigDecimal amount, int clientId, Date date) {
    // CALCULATE COMMISSIONS
    // Rule #1: Default pricing
    BigDecimal rule1Commission = amount.multiply(BigDecimal.valueOf(0.005));
    if (rule1Commission.compareTo(BigDecimal.valueOf(0.05)) == -1)
        rule1Commission = BigDecimal.valueOf(0.05);

    // Rule #2: Client with a discount
    BigDecimal rule2Commission = BigDecimal.ZERO;
    boolean isClientId42 = clientId == 42;
    if (isClientId42)
        rule2Commission = BigDecimal.valueOf(0.05);

    // Rule #3: High turnover discount
    BigDecimal rule3Commission = BigDecimal.ZERO;
    boolean monthlyTurnoverOf1000EUROHasBeenReached = isMonthlyTurnoverOf1000EUROHasBeenReached(amount, date);
    if (monthlyTurnoverOf1000EUROHasBeenReached)
        rule3Commission = BigDecimal.valueOf(0.03);

    // APPLY COMMISSIONS RULES
    CalculatedCommission calculatedCommission;
    if (isClientId42) {
        if (monthlyTurnoverOf1000EUROHasBeenReached) {
            if (rule1Commission.compareTo(rule3Commission) == -1) {
                calculatedCommission = new CalculatedCommission(rule1Commission, RULE1);
            } else {
                calculatedCommission = new CalculatedCommission(rule3Commission, RULE3);
            }
        } else {
            calculatedCommission = new CalculatedCommission(rule2Commission, RULE2);
        }
    } else if (monthlyTurnoverOf1000EUROHasBeenReached) {
        calculatedCommission = new CalculatedCommission(rule3Commission, RULE3);
    } else {
        calculatedCommission = new CalculatedCommission(rule1Commission, RULE1);
    }

    return calculatedCommission;
}

I thought at the beginning given pretty obvious business rules applied for given commissions it could be simply expressed as Strategy pattern where each Rule would be represented by specific Strategy. Although I am quite unsure how could I possibly decide which strategy to choose based on condition as there seems to be one branch where specific commission values are used condition of applying one strategy over another.

I would be grateful for small hint in what direction I could possibly look to get different perspective.

Aucun commentaire:

Enregistrer un commentaire