lundi 12 septembre 2022

How to refactor the code which obey the rule ‘open-closed’?

The UML is down here.There are different products with different preferential strategy. When adding these products into the shoppingcart,it need to call the 'checkout()'method to calcute the 'totalPrice' and 'loyaltyPoints' according to its specific preferential strategy.But when a new product comes with a new preferential strategy,I need to add another 'else if' .I think it break the open-closed principle.So can you give me some advice on how to refactor the code?Thanks, I will wait online.

 public Order checkout() {
    double totalPrice = 0;
    Map<String,Integer> buy2Plus1=new HashMap<>();
    int loyaltyPointsEarned = 0;
    for (Product product : products) {
        double discount = 0;
        if (product.getProductCode().startsWith("DIS_10")) {
            discount = (product.getPrice() * 0.1);
            loyaltyPointsEarned += (product.getPrice() / 10);
        } else if (product.getProductCode().startsWith("DIS_15")) {
            discount = (product.getPrice() * 0.15);
            loyaltyPointsEarned += (product.getPrice() / 15);
        }else if(product.getProductCode().startsWith("DIS_20")){
            discount=(product.getPrice()*0.2);
            loyaltyPointsEarned+=(product.getPrice()/20);
            ...............................................

enter image description here

Aucun commentaire:

Enregistrer un commentaire