lundi 22 janvier 2018

Java - Replacing conditions 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 void setDiscount(String priceCode){
        switch(priceCode){

        case "CODE1" 
                discount = // some logic;
        case "CODE2" 
                discount = // some other logic;
        case "CODE3" 
                discount = // some other logic;

        }
    }

    public int getDiscount(){
        return discount;
    }

}

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

class Product{

String priceCode;
DiscountStrategy discountStrategy;

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

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

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

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?

Aucun commentaire:

Enregistrer un commentaire