Home > OS >  Is this code (creating many classes) causing redundancy?
Is this code (creating many classes) causing redundancy?

Time:12-25

public interface Discount {
    double applyDiscount(double amount);
}

 class StudentDiscount implements Discount {
    @Override
    public double applyDiscount(double amount) {
        return amount * 0.9;
    }
}

 class SeniorCitizenDiscount implements Discount {
    @Override
    public double applyDiscount(double amount) {
        return amount * 0.8;
    }
}

 class BulkOrderDiscount implements Discount {
    private int threshold;
    private double discount;

    public BulkOrderDiscount(int threshold, double discount) {
        this.threshold = threshold;
        this.discount = discount;
    }

    @Override
    public double applyDiscount(double amount) {
        if (amount >= threshold) {
            return amount * (1 - discount);
        } else {
            return amount;
        }
    }
}

here's my code. Is this code legit or anything i can improve to get better efficiency/less redundancy? I'm gonna ask input from user such as: 1)student discount 2)senior discount 3)bulk discount

CodePudding user response:

You don't need three classes, just three instances. So you can do

Discount STUDENT_DISCOUNT = new Discount() {
    @Override
    public double applyDiscount(double amount) {
        return amount * 0.9;
    }
};
public Discount getBulkOrderDiscount(final int threshold, final double discount) {
    return new Discount() {
       @Override
       public double applyDiscount(double amount) {
           if (amount >= threshold) {
               return amount * (1 - discount);
           } else {
               return amount;
           }
       }
    };
}

CodePudding user response:

Since discount is a Functional interface (because it defines a single abstract method) it can be implemented using a Lambda expression.

You can define two method producing Discount implementations:

  • one for discounts based on discount value (like your discounts for students and senior citizens);
  • another for generating bulk-discounts, expecting two arguments threshold and discount.

That's how implementation might look like:

public static Discount createDiscount(double discount) {
    return amount -> amount * discount;
}

public static Discount createBulkDiscount(int threshold, double discount) {
    return amount -> amount >= threshold ? amount * discount : amount;
}

Usage example:

Discount studentDiscount = createDiscount(0.8);
Discount seniorCitizenDiscount = createDiscount(0.9);
Discount bulkDiscount = createBulkDiscount(1_000, 0.75);
    
System.out.println(studentDiscount.applyDiscount(100.0));
System.out.println(seniorCitizenDiscount.applyDiscount(100.0));
System.out.println(bulkDiscount.applyDiscount(300.0));
System.out.println(bulkDiscount.applyDiscount(1_000.0));

Output:

80.0
90.0
300.0
750.0
  • Related