user1298426
user1298426

Reputation: 3717

Replace conditional with polymorphism

I am trying to understand this clean code practice with an example. Consider a class Product having switch case for discount. I am trying to replace switch statement with polymorphism.

Before code:

class Product {
    String priceCode;
    int discount;

    Product(String priceCode) {
        setDiscount(priceCode);
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(String priceCode) {
        switch (priceCode) {
            case "CODE1":
                discount = // some logic;
            case "CODE2":
                discount = // some other logic;
            case "CODE3":
                discount = // some other logic;
        }
    }
}

In below code as you can see I removed switch statement but I still have if conditions to create an object of discountStrategy. My question is I still have if conditions which I am trying to remove with Polymorphism.

After code:

class Product {
    String priceCode;
    DiscountStrategy discountStrategy;

    Product(String priceCode) {
        setDiscount(priceCode);
    }

    public int getDiscount() {
        return discountStrategy.getDiscount();
    }

    public void setDiscount(String priceCode) {
        if (priceCode.equals("CODE1")) {
            discountStrategy = new DiscountStrategy1();
        } else if (priceCode.equals("CODE2")) {
            discountStrategy = new DiscountStrategy2();
        }
        // ...
    }
}

interface DiscountStrategy {
    public int getDiscount();
}

class DiscountStrategy1 implements DiscountStrategy {
    public int getDiscount() {
        // calculate & return discount;
    }
}

class DiscountStrategy2 implements DiscountStrategy {
    public int getDiscount() {
        // calculate & return discount;
    }
}

class DiscountStrategy3 implements DiscountStrategy {
    public int getDiscount() {
        // calculate & return discount;
    }
}

Can you please help me understand this concept with better implementation of this example?

Upvotes: 28

Views: 17359

Answers (4)

Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16276

I think that Product class must not be aware about the discount creation process, it should only use a discount. So, my suggestion is to create a discount factory with a Map that will hold different discount implementations:

class DiscountFactory {
    private static final Map<String, DiscountStrategy> strategies = new HashMap<>();
    private static final DiscountStrategy DEFAULT_STRATEGY = () -> 0;

    static {
        strategies.put("code1", () -> 10);
        strategies.put("code2", () -> 20);
    }

    public DiscountStrategy getDiscountStrategy(String priceCode) {
        if (!strategies.containsKey(priceCode)) {
            return DEFAULT_STRATEGY;
        }
        return strategies.get(priceCode);
    }
}

After that, the Product class can be simplified:

class Product {
    private DiscountStrategy discountStrategy;

    Product(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public int getDiscount() {
        return discountStrategy.getDiscount();
    }
}

Functional interface will allow you to create different implementations using lambda expressions:

interface DiscountStrategy {
    int getDiscount();
}

And finally, example of the use of a product together with discount:

DiscountFactory factory = new DiscountFactory();
Product product = new Product(factory.getDiscountStrategy("code1"));

Upvotes: 39

akshaya pandey
akshaya pandey

Reputation: 997

My two cents: You will need to pass the parameters to discount() method.

a. Create a static class level HashMap of DiscountStrategy. E.g :

map.put("CODE1", new DiscountStrategy1());
map.put("CODE2", new DiscountStrategy2());

b. wherever you need, you can simply use:

map.get(priceCode).discount()

Upvotes: 4

Maurice Perry
Maurice Perry

Reputation: 9658

When, as is seems to be the case in Your example, the discount strategy is bound to a specific product type, I would compute the discount at the order item level. For instance:

class Product {
    double basePrice;
    DiscountStrategy discountStrategy;

...

    public double getBasePrice() {
        return basePrice;
    }

    public DiscountStrategy getDiscountStrategy() {
        return discountStrategy;
    }
}

interface DiscountStrategy {
    public double calculate(int quantity, Product product);
}

class OrderItem {
    int quantity;
    Product product;

    public double getAmount() {
        DiscountStrategy ds = product.getDiscountStrategy();
        double discount = ds.calculate(quantity, product);
        return quantity*(product.getBasePrice() - discount);
    }
}

Example of discount strategy: quantity discount:

class QuantityRateDiscount implements DiscountStrategy {
    static class QuantityRate {
        final int minQuantity;
        final double rate; // in %

        QuantityRate(int minQuantity, double rate) {
            this.minQuantity = minQuantity;
            this.rate = rate;
        }
    }

    QuantityRate[] rateTable;

    // rateTable must be sorted by ascending minQuantity
    QuantityRateDiscount(QuantityRate... rateTable) {
        this.rateTable = rateRable.clone();
    }

    @Override
    public double calculate(int quantity, Product product) {
        QuantityRate qr = null;
        for (QuantityRate qr2: rateTable) {
            if (qr2.minQuantity > quantity) {
                break;
            }
            qr = qr2;
        }
        if (qr != null) {
            return product.getBasePrice()*qr.rate/100.0;
        } else {
            return 0;
        }
    }
}

Upvotes: 0

Mars Moon
Mars Moon

Reputation: 114

Here is what you need to do

    class Product {

    String priceCode;
    DiscountStrategy discountStrategy;

    HashMap<String, DiscountStrategy> map=new HashMap();

    Product(String priceCode) {
        map.put("CODE1", new DiscountStrategy1());
        map.put("CODE2", new DiscountStrategy2());
        map.put("CODE3", new DiscountStrategy3());
        setDiscount(priceCode);
    }

    public void setDiscount(String priceCode){
               discountStrategy=map.get(priceCode);
        }

    public int getDiscount() {
        return discountStrategy.getDiscount();
    }
}

Upvotes: 2

Related Questions