Skip to lesson

Practice: Strategy for discounts and shipping costs

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

ShopLite's checkout total is two changing rules on top of a fixed sum: a discount and a shipping cost. Each rule is a strategy, so marketing can run a new offer and logistics a new courier rate without anyone editing the checkout code.

Discount strategies: percentage, flat and buy-one-get-one

A discount strategy takes an Order and returns how many rupees to take off.

PercentageDiscount takes a share of the subtotal, FlatDiscount takes a fixed amount once the order is big enough, and BuyOneGetOne makes every second unit of one product free.

Example 1 · Three discount strategies on one order

DiscountStrategiesDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.List;
record OrderLine(String sku, String name, BigDecimal price, int qty) {    BigDecimal lineTotal() { return price.multiply(BigDecimal.valueOf(qty)); }}
record Order(List<OrderLine> lines, BigDecimal weightKg, int distanceKm) {    BigDecimal subtotal() {        return lines.stream().map(OrderLine::lineTotal).reduce(BigDecimal.ZERO, BigDecimal::add);    }}
interface DiscountStrategy {    BigDecimal discount(Order order);   // rupees off, never negative}
class NoDiscount implements DiscountStrategy {    public BigDecimal discount(Order order) { return BigDecimal.ZERO; }}
class PercentageDiscount implements DiscountStrategy {    private final BigDecimal percent;    PercentageDiscount(String percent) { this.percent = new BigDecimal(percent); }    public BigDecimal discount(Order order) {        return order.subtotal().multiply(percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);    }}
class FlatDiscount implements DiscountStrategy {    private final BigDecimal off, minOrder;    FlatDiscount(String off, String minOrder) { this.off = new BigDecimal(off); this.minOrder = new BigDecimal(minOrder); }    public BigDecimal discount(Order order) {        return order.subtotal().compareTo(minOrder) >= 0 ? off : BigDecimal.ZERO;    }}
class BuyOneGetOne implements DiscountStrategy {    private final String sku;    BuyOneGetOne(String sku) { this.sku = sku; }    public BigDecimal discount(Order order) {        return order.lines().stream()                .filter(l -> l.sku().equals(sku))                .map(l -> l.price().multiply(BigDecimal.valueOf(l.qty() / 2)))                .reduce(BigDecimal.ZERO, BigDecimal::add);    }}
public class DiscountStrategiesDemo {    public static void main(String[] args) {        Order order = new Order(List.of(                new OrderLine("TSHIRT", "Cotton T-shirt", new BigDecimal("399.00"), 3),                new OrderLine("MUG", "Coffee mug", new BigDecimal("249.00"), 1)),                new BigDecimal("1.2"), 8);        System.out.println("Subtotal: Rs " + order.subtotal());
        List<DiscountStrategy> offers = List.of(                new PercentageDiscount("10"),                new FlatDiscount("150.00", "999.00"),                new BuyOneGetOne("TSHIRT"));        for (DiscountStrategy offer : offers) {            System.out.println(offer.getClass().getSimpleName() + ": Rs " + offer.discount(order) + " off");        }    }}
Output
Subtotal: Rs 1446.00
PercentageDiscount: Rs 144.60 off
FlatDiscount: Rs 150.00 off
BuyOneGetOne: Rs 399.00 off

What this code does

  • One order, three strategies, one loop: the caller never asks which kind of discount it holds.
  • 10% of Rs 1446.00 is Rs 144.60, divided with scale 2 and HALF_UP. The flat Rs 150 applies because the subtotal is at least Rs 999.
  • Three T-shirts give one free (3 / 2 = 1 in integer division), so buy-one-get-one takes off Rs 399.00.

All three return a BigDecimal amount, never a new total. Returning "rupees off" keeps each strategy small and lets the calculator decide how discounts and shipping combine.

Shipping strategies: weight, distance and a free-shipping threshold

A shipping strategy returns the delivery cost for an order.

WeightShipping charges Rs 40 for the first kilogram and Rs 15 for every started extra kilogram; DistanceShipping charges by zone (up to 5 km, up to 20 km, beyond).

Example 2 · Weight, distance and free-shipping rules

ShippingStrategiesDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.List;
record OrderLine(String sku, String name, BigDecimal price, int qty) {    BigDecimal lineTotal() { return price.multiply(BigDecimal.valueOf(qty)); }}
record Order(List<OrderLine> lines, BigDecimal weightKg, int distanceKm) {    BigDecimal subtotal() {        return lines.stream().map(OrderLine::lineTotal).reduce(BigDecimal.ZERO, BigDecimal::add);    }}
interface ShippingStrategy {    BigDecimal cost(Order order, BigDecimal amountAfterDiscount);}
class WeightShipping implements ShippingStrategy {    public BigDecimal cost(Order order, BigDecimal amountAfterDiscount) {        int kg = order.weightKg().setScale(0, RoundingMode.CEILING).intValue();        return BigDecimal.valueOf(40 + Math.max(0, kg - 1) * 15L);   // Rs 40 first kg, Rs 15 per extra started kg    }}
class DistanceShipping implements ShippingStrategy {    public BigDecimal cost(Order order, BigDecimal amountAfterDiscount) {        int km = order.distanceKm();        return BigDecimal.valueOf(km <= 5 ? 30 : km <= 20 ? 60 : 120);    }}
class FreeShippingAbove implements ShippingStrategy {    private final BigDecimal threshold;    private final ShippingStrategy inner;    FreeShippingAbove(String threshold, ShippingStrategy inner) { this.threshold = new BigDecimal(threshold); this.inner = inner; }    public BigDecimal cost(Order order, BigDecimal amountAfterDiscount) {        return amountAfterDiscount.compareTo(threshold) >= 0 ? BigDecimal.ZERO : inner.cost(order, amountAfterDiscount);    }}
public class ShippingStrategiesDemo {    public static void main(String[] args) {        Order light = new Order(List.of(new OrderLine("MUG", "Coffee mug", new BigDecimal("249.00"), 1)), new BigDecimal("0.4"), 3);        Order heavy = new Order(List.of(new OrderLine("STAND", "Laptop stand set 5 kg", new BigDecimal("650.00"), 1)), new BigDecimal("5.3"), 25);
        ShippingStrategy byWeight = new WeightShipping();        ShippingStrategy byDistance = new DistanceShipping();        ShippingStrategy freeAbove499 = new FreeShippingAbove("499.00", byWeight);
        for (Order o : List.of(light, heavy)) {            String name = o.lines().get(0).name();            System.out.println(name + " (" + o.weightKg() + " kg, " + o.distanceKm() + " km):"                    + " weight Rs " + byWeight.cost(o, o.subtotal())                    + ", distance Rs " + byDistance.cost(o, o.subtotal())                    + ", free above 499 Rs " + freeAbove499.cost(o, o.subtotal()));        }    }}
Output
Coffee mug (0.4 kg, 3 km): weight Rs 40, distance Rs 30, free above 499 Rs 40
Laptop stand set 5 kg (5.3 kg, 25 km): weight Rs 115, distance Rs 120, free above 499 Rs 0

What this code does

  • 5.3 kg rounds up to 6 started kilograms with RoundingMode.CEILING: Rs 40 + 5 × Rs 15 = Rs 115.
  • FreeShippingAbove wraps the weight strategy: the light Rs 249 order still pays weight shipping, the Rs 650 order ships free.
  • Because the wrapper takes any ShippingStrategy, "free above 499" can sit on top of distance pricing with no new code.

"Free shipping above Rs 499" is not a third rate: it is a rule that wraps another strategy. FreeShippingAbove returns 0 when the amount is high enough and otherwise asks the wrapped strategy, so it works with weight or distance pricing alike.

Combining strategies for a final total with BigDecimal

The price calculator is the one class that combines the rules: subtotal, minus the discount (never more than the subtotal), plus shipping on the discounted amount, rounded to 2 decimal places.

PriceCalculator receives one DiscountStrategy and one ShippingStrategy in its constructor.

Example 3 · The price calculator combines both rules

PriceCalculatorDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.List;
record OrderLine(String sku, String name, BigDecimal price, int qty) {    BigDecimal lineTotal() { return price.multiply(BigDecimal.valueOf(qty)); }}
record Order(List<OrderLine> lines, BigDecimal weightKg, int distanceKm) {    BigDecimal subtotal() {        return lines.stream().map(OrderLine::lineTotal).reduce(BigDecimal.ZERO, BigDecimal::add);    }}
interface DiscountStrategy {    BigDecimal discount(Order order);   // rupees off, never negative}
class NoDiscount implements DiscountStrategy {    public BigDecimal discount(Order order) { return BigDecimal.ZERO; }}
class PercentageDiscount implements DiscountStrategy {    private final BigDecimal percent;    PercentageDiscount(String percent) { this.percent = new BigDecimal(percent); }    public BigDecimal discount(Order order) {        return order.subtotal().multiply(percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);    }}
class FlatDiscount implements DiscountStrategy {    private final BigDecimal off, minOrder;    FlatDiscount(String off, String minOrder) { this.off = new BigDecimal(off); this.minOrder = new BigDecimal(minOrder); }    public BigDecimal discount(Order order) {        return order.subtotal().compareTo(minOrder) >= 0 ? off : BigDecimal.ZERO;    }}
class BuyOneGetOne implements DiscountStrategy {    private final String sku;    BuyOneGetOne(String sku) { this.sku = sku; }    public BigDecimal discount(Order order) {        return order.lines().stream()                .filter(l -> l.sku().equals(sku))                .map(l -> l.price().multiply(BigDecimal.valueOf(l.qty() / 2)))                .reduce(BigDecimal.ZERO, BigDecimal::add);    }}
interface ShippingStrategy {    BigDecimal cost(Order order, BigDecimal amountAfterDiscount);}
class WeightShipping implements ShippingStrategy {    public BigDecimal cost(Order order, BigDecimal amountAfterDiscount) {        int kg = order.weightKg().setScale(0, RoundingMode.CEILING).intValue();        return BigDecimal.valueOf(40 + Math.max(0, kg - 1) * 15L);   // Rs 40 first kg, Rs 15 per extra started kg    }}
class DistanceShipping implements ShippingStrategy {    public BigDecimal cost(Order order, BigDecimal amountAfterDiscount) {        int km = order.distanceKm();        return BigDecimal.valueOf(km <= 5 ? 30 : km <= 20 ? 60 : 120);    }}
class FreeShippingAbove implements ShippingStrategy {    private final BigDecimal threshold;    private final ShippingStrategy inner;    FreeShippingAbove(String threshold, ShippingStrategy inner) { this.threshold = new BigDecimal(threshold); this.inner = inner; }    public BigDecimal cost(Order order, BigDecimal amountAfterDiscount) {        return amountAfterDiscount.compareTo(threshold) >= 0 ? BigDecimal.ZERO : inner.cost(order, amountAfterDiscount);    }}
class PriceCalculator {    private final DiscountStrategy discount;    private final ShippingStrategy shipping;
    PriceCalculator(DiscountStrategy discount, ShippingStrategy shipping) {        this.discount = discount;        this.shipping = shipping;    }
    BigDecimal total(Order order, boolean print) {        BigDecimal subtotal = order.subtotal();        BigDecimal off = discount.discount(order).min(subtotal);   // a discount never goes below zero        BigDecimal afterDiscount = subtotal.subtract(off);        BigDecimal ship = shipping.cost(order, afterDiscount);        BigDecimal total = afterDiscount.add(ship).setScale(2, RoundingMode.HALF_UP);        if (print) {            System.out.println("  Subtotal  Rs " + subtotal.setScale(2));            System.out.println("  Discount -Rs " + off.setScale(2));            System.out.println("  Shipping  Rs " + ship.setScale(2));            System.out.println("  Total     Rs " + total);        }        return total;    }}
public class PriceCalculatorDemo {    public static void main(String[] args) {        Order order = new Order(List.of(                new OrderLine("NOTEBOOK", "A4 notebook", new BigDecimal("65.00"), 8)),                new BigDecimal("2.4"), 12);        ShippingStrategy shipping = new FreeShippingAbove("499.00", new WeightShipping());
        System.out.println("No offer:");        new PriceCalculator(new NoDiscount(), shipping).total(order, true);        System.out.println("With FLAT50 (min Rs 500):");        new PriceCalculator(new FlatDiscount("50.00", "500.00"), shipping).total(order, true);    }}
Output
No offer:
  Subtotal  Rs 520.00
  Discount -Rs 0.00
  Shipping  Rs 0.00
  Total     Rs 520.00
With FLAT50 (min Rs 500):
  Subtotal  Rs 520.00
  Discount -Rs 50.00
  Shipping  Rs 70.00
  Total     Rs 540.00

What this code does

  • Eight notebooks cost Rs 520.00, above the Rs 499 threshold, so with no offer shipping is free.
  • With Rs 50 off, the discounted amount is Rs 470.00, below the threshold, so weight shipping applies (2.4 kg → 3 started kg → Rs 70) and the coupon makes the total Rs 20 higher. The order of steps changes real totals, which is why it is agreed and written down.
  • The calculator only adds and subtracts; it has no idea which offer or courier rate it was given.

The order of steps is a business rule, so write it down: ShopLite checks the free-shipping threshold after the discount, so a Rs 520 cart with Rs 50 off pays shipping. Use compareTo for every money comparison and setScale(2, RoundingMode.HALF_UP) once, at the end.

Fix the error

Check the threshold on the right amount

Free shipping starts at Rs 499 on the amount after the discount. Pick the fix.

A Rs 520 cart with a Rs 50 coupon should pay shipping.

BigDecimal off = discount.discount(order);
BigDecimal after = subtotal.subtract(off);
BigDecimal ship = shipping.cost(order, subtotal);

Error

Wrong result: the Rs 470 cart ships free

Adding a festival discount without editing existing classes

The open/closed principle says code should be open for extension but closed for modification: new behaviour arrives as new classes.

A Diwali offer (10% off, at most Rs 300, only from 1 to 10 November) is a new FestivalDiscount class; nothing else changes.

Example 4 · A festival discount and a best-of composite

FestivalDiscountDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.time.Clock;import java.time.Instant;import java.time.LocalDate;import java.time.ZoneId;import java.util.Comparator;import java.util.List;
record OrderLine(String sku, String name, BigDecimal price, int qty) {    BigDecimal lineTotal() { return price.multiply(BigDecimal.valueOf(qty)); }}
record Order(List<OrderLine> lines, BigDecimal weightKg, int distanceKm) {    BigDecimal subtotal() {        return lines.stream().map(OrderLine::lineTotal).reduce(BigDecimal.ZERO, BigDecimal::add);    }}
interface DiscountStrategy {    BigDecimal discount(Order order);   // rupees off, never negative}
class NoDiscount implements DiscountStrategy {    public BigDecimal discount(Order order) { return BigDecimal.ZERO; }}
class PercentageDiscount implements DiscountStrategy {    private final BigDecimal percent;    PercentageDiscount(String percent) { this.percent = new BigDecimal(percent); }    public BigDecimal discount(Order order) {        return order.subtotal().multiply(percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);    }}
class FlatDiscount implements DiscountStrategy {    private final BigDecimal off, minOrder;    FlatDiscount(String off, String minOrder) { this.off = new BigDecimal(off); this.minOrder = new BigDecimal(minOrder); }    public BigDecimal discount(Order order) {        return order.subtotal().compareTo(minOrder) >= 0 ? off : BigDecimal.ZERO;    }}
class BuyOneGetOne implements DiscountStrategy {    private final String sku;    BuyOneGetOne(String sku) { this.sku = sku; }    public BigDecimal discount(Order order) {        return order.lines().stream()                .filter(l -> l.sku().equals(sku))                .map(l -> l.price().multiply(BigDecimal.valueOf(l.qty() / 2)))                .reduce(BigDecimal.ZERO, BigDecimal::add);    }}
// New class: nothing above this line changedclass FestivalDiscount implements DiscountStrategy {    private final BigDecimal percent, cap;    private final LocalDate from, to;    private final Clock clock;
    FestivalDiscount(String percent, String cap, LocalDate from, LocalDate to, Clock clock) {        this.percent = new BigDecimal(percent);        this.cap = new BigDecimal(cap);        this.from = from;        this.to = to;        this.clock = clock;    }
    public BigDecimal discount(Order order) {        LocalDate today = LocalDate.now(clock);        if (today.isBefore(from) || today.isAfter(to)) return BigDecimal.ZERO;        BigDecimal off = order.subtotal().multiply(percent).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);        return off.min(cap);    }}
class BestOfDiscounts implements DiscountStrategy {    private final List<DiscountStrategy> options;    BestOfDiscounts(List<DiscountStrategy> options) { this.options = options; }    public BigDecimal discount(Order order) {        return options.stream().map(d -> d.discount(order)).max(Comparator.naturalOrder()).orElse(BigDecimal.ZERO);    }}
public class FestivalDiscountDemo {    static Clock on(String date) {        return Clock.fixed(Instant.parse(date + "T06:00:00Z"), ZoneId.of("Asia/Kolkata"));    }
    public static void main(String[] args) {        Order order = new Order(List.of(new OrderLine("LAMP", "Diya lamp set", new BigDecimal("899.00"), 4)), new BigDecimal("3"), 10);        LocalDate from = LocalDate.of(2026, 11, 1), to = LocalDate.of(2026, 11, 10);
        for (String day : List.of("2026-10-28", "2026-11-05")) {            DiscountStrategy diwali = new FestivalDiscount("10", "300.00", from, to, on(day));            DiscountStrategy best = new BestOfDiscounts(List.of(diwali, new FlatDiscount("200.00", "2000.00")));            System.out.println(day + ": Diwali Rs " + diwali.discount(order) + ", best offer Rs " + best.discount(order));        }    }}
Output
2026-10-28: Diwali Rs 0, best offer Rs 200.00
2026-11-05: Diwali Rs 300.00, best offer Rs 300.00

What this code does

  • FestivalDiscount is a new class; the interface, the other discounts and the calculator are untouched. That is the open/closed principle in practice.
  • On 5 November, 10% of Rs 3596.00 is Rs 359.60, capped at Rs 300.00. On 28 October the festival has not started, so it gives 0 and the best offer is the flat Rs 200.
  • BestOfDiscounts is itself a DiscountStrategy holding others (a small Composite), and the fixed Clock makes "today" the same on every run.

When two offers apply, a small composite strategy, BestOfDiscounts, holds several strategies and returns the biggest discount. The calculator still sees one DiscountStrategy. The festival dates come from a java.time.Clock passed in, so tests can fix "today".

Predict the output

Best of, or one after the other

A 10% discount and a flat Rs 100 discount on a Rs 800 order.

Round 1 of 2

BestOfDiscounts returns the bigger of the two. How much is taken off?

BigDecimal tenPercent = new BigDecimal("80.00");
BigDecimal flat = new BigDecimal("100.00");
System.out.println(tenPercent.max(flat));

Finish up

Mark complete & continue

Next: Practice: order notification events