Site icon NexGismo

Open Closed Principle in Java: Tax Rules Without Edits

Open Closed Principle in Java: Tax Rules Without Edits

OOP in Practice · Episode 10 of 70 · SOLID Principles · Intermediate · Java 21.0.13.1

The problem

You maintain the checkout of a shop that sells in the UK, Germany and India. Every launch in a new country means editing one shared TaxCalculator, and the open closed principle is exactly what that class breaks. A forgotten case once taxed a new country at zero, and Germany’s food rate does not fit at all.

Your task: redesign the calculator so a new country’s tax rule is added as new code, and the calculator itself never changes.

Requirements

  • Return each tax line and the gross total for an order, by country.
  • Support three rule shapes: flat rate (UK), reduced rate for food (DE), and a same-state split versus one cross-state tax (IN).
  • Add AE (flat rate) and SG (small-order exemption) without editing the calculator or any existing rule.
  • Prove the old countries give identical results afterwards.
  • Reject an unknown country, a duplicate rule, a non-positive amount, and an Indian order with no state.

Constraints and assumptions

  • Single process, in memory, plain Java 21 with no libraries.
  • Money is whole minor units of each currency. Rates are basis points: 1800 means 18%.
  • All rates and rules are simplified practice values, not current tax law or tax advice.

What this tests: open/closed principle, strategy, plugins, interfaces, composition, records, regression testing

The open closed principle says code should be open for extension but closed for modification. Put each country’s tax rule behind a TaxRule interface. A final TaxCalculator looks rules up by country and contains no country logic. A new market is a new rule object registered at startup, so tested code never changes.

Try it yourself first — hint

Find the line you edit at every launch. Whatever it decides should become an object the calculator asks.

Step 1: Identify the objects and responsibilities

Martin’s 2014 restatement: extend a system’s behaviour without modifying it. So find what varies first. Here it is how a country turns an order into tax lines.

Tax classes after the refactor, split into the closed core and the open edge
Class / interface Responsibility Key methods
TaxRule (interface) The extension point. One country’s way of taxing an order. country(), taxes(Order)
TaxCalculator (final) Registers rules, rejects duplicates, finds the rule. Knows no country. calculate(), countries()
FlatVat, ReducedRateVat, IndiaGst One rule shape each; UK and AE share FlatVat. taxes()
ExemptBelow Wraps any rule and skips tax below a threshold. Extension by composition. taxes()
Line, Order Immutable input data. Reject bad amounts and empty orders. netCents()
TaxLine, TaxBreakdown Immutable result, compared by value. grossCents()

Step 2: The naive approach and why it breaks

public class Naive {
    public static void main(String[] args) {
        TaxCalculator calc = new TaxCalculator();
        System.out.println("UK " + calc.tax("UK", null, 4999));
        System.out.println("IN " + calc.tax("IN", "KA", 100000));
        System.out.println("AE " + calc.tax("AE", null, 20000)); // new market, forgot the case
    }
}

class TaxCalculator {
    // Every new country = edit this method, re-test every country.
    long tax(String country, String state, long netCents) {
        switch (country) {
            case "UK": return Math.round(netCents * 0.20);
            case "DE": return Math.round(netCents * 0.19);   // food at 7%? not handled
            case "IN":
                if ("KA".equals(state)) return Math.round(netCents * 0.09) * 2; // CGST + SGST
                return Math.round(netCents * 0.18);                             // IGST
            default:
                return 0;   // unknown country: silently tax-free
        }
    }
}

Run with java Naive.java, it printed:

UK 1000
IN 18000
AE 0

Step 3: The design

           +-------------------------------------+
           | TaxCalculator        (final class)  |
           | calculate(Order): TaxBreakdown      |
           | countries(): List<String>           |
           +-------------------------------------+
                    | holds Map<country, TaxRule>  (closed)
                    v
           +-------------------------------------+
           | <<interface>> TaxRule               |  <- extension point
           | country(): String                   |
           | taxes(Order): List<TaxLine>         |
           +-------------------------------------+
              ^           ^            ^            ^     (open)
              | implements|            |            |
       +----------+ +--------------+ +----------+ +---------------------+
       | FlatVat  | | ReducedRate  | | IndiaGst | | ExemptBelow         |
       | UK, AE   | | Vat  (DE)    | | (IN)     | | wraps any TaxRule   |
       +----------+ +--------------+ +----------+ +---------------------+

  Order(country, region, List<Line>)  -->  TaxBreakdown(where, net, taxes)

Bertrand Meyer coined the term in 1988, using implementation inheritance. The 1990s redefinition, including Martin’s 1996 article, uses abstract interfaces and polymorphism. That is the version used here.

Structurally this is the strategy pattern. The focus here is different: which code stays closed, how a market plugs in, and how you prove old behaviour did not move. Following the single responsibility principle, the calculator only finds and calls a rule.

Step 4: The open closed principle solution in Java

import java.util.*;

/** Demo: the calculator never changes; new countries arrive as new TaxRule objects. */
public class Main {
    public static void main(String[] args) {
        List<TaxRule> launch = List.of(
            new FlatVat("UK", "VAT", 2000),
            new ReducedRateVat("DE", 1900, Map.of(Category.FOOD, 700)),
            new IndiaGst(1800, "KA"));
        TaxCalculator v1 = new TaxCalculator(launch);

        List<Order> orders = List.of(
            new Order("UK", "", List.of(new Line("Desk lamp", Category.GOODS, 4999))),
            new Order("DE", "", List.of(new Line("Kettle", Category.GOODS, 8000),
                                        new Line("Coffee beans", Category.FOOD, 2000))),
            new Order("IN", "KA", List.of(new Line("Headphones", Category.GOODS, 100000))),
            new Order("IN", "MH", List.of(new Line("Headphones", Category.GOODS, 100000))));
        System.out.println("v1 countries: " + v1.countries());
        orders.forEach(o -> System.out.println(v1.calculate(o)));

        // Extension: two new markets, zero edits to TaxCalculator or existing rules.
        List<TaxRule> plus = new ArrayList<>(launch);
        plus.add(new FlatVat("AE", "VAT", 500));                                // configuration
        plus.add(new ExemptBelow(new FlatVat("SG", "GST", 900), 10000));        // new class
        TaxCalculator v2 = new TaxCalculator(plus);
        System.out.println("\nv2 countries: " + v2.countries());
        System.out.println(v2.calculate(new Order("AE", "", List.of(new Line("Monitor", Category.GOODS, 60000)))));
        System.out.println(v2.calculate(new Order("SG", "", List.of(new Line("Cable", Category.GOODS, 2500)))));
        System.out.println(v2.calculate(new Order("SG", "", List.of(new Line("Chair", Category.GOODS, 25000)))));

        long same = orders.stream().filter(o -> v1.calculate(o).equals(v2.calculate(o))).count();
        System.out.println("Old orders unchanged in v2: " + same + " of " + orders.size());

        System.out.println("\nEdge cases:");
        attempt("unknown country", () -> v2.calculate(new Order("FR", "", List.of(new Line("Book", Category.GOODS, 1500)))));
        attempt("duplicate rule", () -> new TaxCalculator(List.of(new FlatVat("UK", "VAT", 2000), new FlatVat("UK", "VAT", 500))));
        attempt("negative amount", () -> new Line("Refund", Category.GOODS, -100));
        attempt("IN without state", () -> v2.calculate(new Order("IN", "", List.of(new Line("Mouse", Category.GOODS, 50000)))));
    }

    static void attempt(String label, Runnable action) {
        try { action.run(); System.out.printf("%-16s -> accepted (unexpected)%n", label); }
        catch (IllegalArgumentException e) { System.out.printf("%-16s -> %s%n", label, e.getMessage()); }
    }
}

enum Category { GOODS, FOOD }

record Line(String name, Category category, long netCents) {
    Line {
        if (netCents <= 0) throw new IllegalArgumentException("net must be > 0, got " + netCents);
    }
}

record Order(String country, String region, List<Line> lines) {
    Order {
        if (lines.isEmpty()) throw new IllegalArgumentException("order has no lines");
        lines = List.copyOf(lines);
    }
    long netCents() { return lines.stream().mapToLong(Line::netCents).sum(); }
}

record TaxLine(String label, long cents) {}

record TaxBreakdown(String where, long netCents, List<TaxLine> taxes) {
    long grossCents() { return netCents + taxes.stream().mapToLong(TaxLine::cents).sum(); }
    static String money(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }
    @Override public String toString() {
        List<String> parts = taxes.stream().map(t -> t.label() + " " + money(t.cents())).toList();
        return String.format("%-5s net %7s | %s | gross %7s", where, money(netCents),
                parts.isEmpty() ? "no tax" : String.join(", ", parts), money(grossCents()));
    }
}

/** The extension point. Each country's rule is one object behind this interface. */
interface TaxRule {
    String country();
    List<TaxLine> taxes(Order order);

    /** basis points: 1800 = 18%. Rounds half up; amounts are positive. */
    static long percentOf(long cents, int bp) { return Math.addExact(Math.multiplyExact(cents, bp), 5000) / 10000; }
    static String pct(int bp) { return bp % 100 == 0 ? (bp / 100) + "%" : (bp / 100.0) + "%"; }
}

/** Closed for modification: knows nothing about any specific country. */
final class TaxCalculator {
    private final Map<String, TaxRule> rules;

    TaxCalculator(Collection<TaxRule> rules) {
        Map<String, TaxRule> byCountry = new HashMap<>();
        for (TaxRule r : rules) {
            if (byCountry.putIfAbsent(r.country(), r) != null)
                throw new IllegalArgumentException("duplicate rule for " + r.country());
        }
        this.rules = Map.copyOf(byCountry);
    }

    List<String> countries() { return rules.keySet().stream().sorted().toList(); }

    TaxBreakdown calculate(Order order) {
        TaxRule rule = rules.get(order.country());
        if (rule == null) throw new IllegalArgumentException("no tax rule registered for " + order.country());
        String where = order.region().isBlank() ? order.country() : order.country() + "/" + order.region();
        return new TaxBreakdown(where, order.netCents(), rule.taxes(order));
    }
}

record FlatVat(String country, String label, int bp) implements TaxRule {
    public List<TaxLine> taxes(Order o) {
        return List.of(new TaxLine(label + " " + TaxRule.pct(bp), TaxRule.percentOf(o.netCents(), bp)));
    }
}

record ReducedRateVat(String country, int standardBp, Map<Category, Integer> reducedBp) implements TaxRule {
    ReducedRateVat { reducedBp = Map.copyOf(reducedBp); }
    public List<TaxLine> taxes(Order o) {
        Map<Integer, Long> netByRate = new TreeMap<>(Comparator.reverseOrder());
        for (Line l : o.lines()) netByRate.merge(reducedBp.getOrDefault(l.category(), standardBp), l.netCents(), Long::sum);
        List<TaxLine> out = new ArrayList<>();
        netByRate.forEach((bp, net) -> out.add(new TaxLine("VAT " + TaxRule.pct(bp), TaxRule.percentOf(net, bp))));
        return out;
    }
}

record IndiaGst(int bp, String homeState) implements TaxRule {
    public String country() { return "IN"; }
    public List<TaxLine> taxes(Order o) {
        if (o.region().isBlank()) throw new IllegalArgumentException("IN orders need a ship-to state");
        if (!o.region().equals(homeState)) return List.of(new TaxLine("IGST " + TaxRule.pct(bp), TaxRule.percentOf(o.netCents(), bp)));
        long half = TaxRule.percentOf(o.netCents(), bp / 2);
        return List.of(new TaxLine("CGST " + TaxRule.pct(bp / 2), half), new TaxLine("SGST " + TaxRule.pct(bp / 2), half));
    }
}

/** Extension by composition: wraps any rule, adds a small-order exemption. */
record ExemptBelow(TaxRule inner, long thresholdCents) implements TaxRule {
    public String country() { return inner.country(); }
    public List<TaxLine> taxes(Order o) { return o.netCents() < thresholdCents ? List.of() : inner.taxes(o); }
}

Step 5: Run it and check the output

v1 countries: [DE, IN, UK]
UK    net   49.99 | VAT 20% 10.00 | gross   59.99
DE    net  100.00 | VAT 19% 15.20, VAT 7% 1.40 | gross  116.60
IN/KA net 1000.00 | CGST 9% 90.00, SGST 9% 90.00 | gross 1180.00
IN/MH net 1000.00 | IGST 18% 180.00 | gross 1180.00

v2 countries: [AE, DE, IN, SG, UK]
AE    net  600.00 | VAT 5% 30.00 | gross  630.00
SG    net   25.00 | no tax | gross   25.00
SG    net  250.00 | GST 9% 22.50 | gross  272.50
Old orders unchanged in v2: 4 of 4

Edge cases:
unknown country  -> no tax rule registered for FR
duplicate rule   -> duplicate rule for UK
negative amount  -> net must be > 0, got -100
IN without state -> IN orders need a ship-to state

Tested: Java openjdk 21.0.13.1 — java Main.java, 2026-11-30. Output above is copied from that run.

“Old orders unchanged in v2: 4 of 4” is the point of the episode: a plain equals on record results. A separate assert run also passed: half a cent rounds up, SG 99.99 is exempt and 100.00 is taxed, and overflow throws.

Why this design works

Trade-offs, edge cases and when not to use it

Option Good when Cost
switch on country Two or three stable countries Every launch edits it; a missed case returns a silent default
Rule objects behind an interface (this episode) Markets launch often and rules differ in shape More types; startup code must list every rule
Config table only Every country fits one formula Breaks when one needs a different shape, like India’s split
Sealed interface with a permits list The set should be fixed and reviewed in one place Deliberately closed: a new rule edits the list
ServiceLoader plugins Rules ship in separate jars or modules Registration errors appear only at startup

Two edge cases stay open. IndiaGst halves the rate, which suits even basis points only. And the design is closed against new countries, not new inputs: if tax depends on customer type, Order must grow. Martin’s 2013 reply says no significant program is 100% closed. My recommendation: keep the switch until the third market, then extract the interface.

Interview follow-up questions

Can any class be fully closed for modification?

No. Martin’s answer is strategic closure: close a module against the kinds of change you expect. This calculator is closed against a new country or rule shape. It is not closed against tax depending on the customer’s VAT number, because TaxRule only sees an Order. The freeCodeCamp walkthrough suggests weighing how likely each change is before abstracting.

How would you add rules without recompiling the core?

Ship each rule as a provider of a TaxRule service. List providers in a META-INF/services file, or declare provides … with … in a module; the ServiceLoader docs cover both. At startup, load the providers and pass them to the existing constructor, which already rejects duplicates. Martin cites IDE plugins as the same idea.

How do you test that a new country didn’t break the old ones?

Three layers. Unit-test each rule, including boundaries such as the SG threshold. Write one contract test every TaxRule must pass, such as no negative tax. Then keep fixed orders per country and compare breakdowns before and after the change, as the demo does. With record results, that is value equality.

The same solution in TypeScript

Show the TypeScript version
type Category = "goods" | "food";
interface Line { readonly name: string; readonly category: Category; readonly netCents: number; }
interface Order { readonly country: string; readonly region: string; readonly lines: readonly Line[]; }
interface TaxLine { readonly label: string; readonly cents: number; }

/** The extension point: one object per country rule. */
interface TaxRule {
  readonly country: string;
  taxes(order: Order): TaxLine[];
}

const net = (o: Order): number => o.lines.reduce((sum, l) => sum + l.netCents, 0);
const percentOf = (cents: number, bp: number): number => Math.floor((cents * bp + 5000) / 10000);
const money = (c: number): string => `${Math.floor(c / 100)}.${String(c % 100).padStart(2, "0")}`;

class FlatVat implements TaxRule {
  constructor(readonly country: string, private readonly label: string, private readonly bp: number) {}
  taxes(o: Order): TaxLine[] { return [{ label: `${this.label} ${this.bp / 100}%`, cents: percentOf(net(o), this.bp) }]; }
}

class IndiaGst implements TaxRule {
  readonly country = "IN";
  constructor(private readonly bp: number, private readonly homeState: string) {}
  taxes(o: Order): TaxLine[] {
    if (o.region === "") throw new Error("IN orders need a ship-to state");
    if (o.region !== this.homeState) return [{ label: `IGST ${this.bp / 100}%`, cents: percentOf(net(o), this.bp) }];
    const half = percentOf(net(o), this.bp / 2);
    return [{ label: `CGST ${this.bp / 200}%`, cents: half }, { label: `SGST ${this.bp / 200}%`, cents: half }];
  }
}

class ExemptBelow implements TaxRule {
  constructor(private readonly inner: TaxRule, private readonly thresholdCents: number) {}
  get country(): string { return this.inner.country; }
  taxes(o: Order): TaxLine[] { return net(o) < this.thresholdCents ? [] : this.inner.taxes(o); }
}

/** Closed for modification: no country names in here. */
class TaxCalculator {
  private readonly rules = new Map<string, TaxRule>();
  constructor(rules: readonly TaxRule[]) {
    for (const r of rules) {
      if (this.rules.has(r.country)) throw new Error(`duplicate rule for ${r.country}`);
      this.rules.set(r.country, r);
    }
  }
  calculate(o: Order): string {
    const rule = this.rules.get(o.country);
    if (!rule) throw new Error(`no tax rule registered for ${o.country}`);
    const taxes = rule.taxes(o);
    const gross = net(o) + taxes.reduce((s, t) => s + t.cents, 0);
    const parts = taxes.map(t => `${t.label} ${money(t.cents)}`).join(", ") || "no tax";
    const where = o.region ? `${o.country}/${o.region}` : o.country;
    return `${where.padEnd(5)} net ${money(net(o)).padStart(7)} | ${parts} | gross ${money(gross).padStart(7)}`;
  }
}

const order = (country: string, region: string, cents: number): Order =>
  ({ country, region, lines: [{ name: "item", category: "goods", netCents: cents }] });

const calc = new TaxCalculator([
  new FlatVat("UK", "VAT", 2000),
  new IndiaGst(1800, "KA"),
  new FlatVat("AE", "VAT", 500),
  new ExemptBelow(new FlatVat("SG", "GST", 900), 10000),
]);
for (const o of [order("UK", "", 4999), order("IN", "KA", 100000), order("IN", "MH", 100000),
                 order("AE", "", 60000), order("SG", "", 2500), order("SG", "", 25000)]) {
  console.log(calc.calculate(o));
}
try { calc.calculate(order("FR", "", 1500)); } catch (e) { console.log(`unknown country -> ${(e as Error).message}`); }
UK    net   49.99 | VAT 20% 10.00 | gross   59.99
IN/KA net 1000.00 | CGST 9% 90.00, SGST 9% 90.00 | gross 1180.00
IN/MH net 1000.00 | IGST 18% 180.00 | gross 1180.00
AE    net  600.00 | VAT 5% 30.00 | gross  630.00
SG    net   25.00 | no tax | gross   25.00
SG    net  250.00 | GST 9% 22.50 | gross  272.50
unknown country -> no tax rule registered for FR

TypeScript 7.0.2 on Node v22.23.5. An implements clause checks each rule against TaxRule; a Map keeps insertion order. The German rule is omitted for length.

Practice: extend it yourself

  1. Launch FR with configuration only: new ReducedRateVat("FR", 2000, Map.of(Category.FOOD, 550)). Expected behaviour: an order with 80.00 of goods and 20.00 of food prints VAT 20% 16.00, VAT 5.5% 1.10, and no existing class changes.
  2. Write a CappedTax rule that wraps another rule and limits its tax. Expected behaviour: AE capped at 20.00 charges 20.00 on the 600.00 monitor; old orders stay 4 of 4.
  3. Load flat-rate rules from lines such as AE,VAT,500. Expected behaviour: a malformed line is rejected with its line number; a repeated country is still rejected by the unchanged constructor.

Frequently Asked Questions

What is the open closed principle?

It is the O in SOLID: software entities should be open for extension but closed for modification. Bertrand Meyer coined the term in 1988. Robert C. Martin restated it as adding new behaviour by writing new code, without editing code that already works.

Does the open closed principle mean you can never change existing code?

No. Martin calls the strict wording overstated. You still fix bugs and refactor. The goal is that expected changes, such as a new country's tax rule, arrive as new classes. No program is closed against every change, so you choose which ones to protect against.

What is a simple example of the open closed principle in Java?

A tax calculator that holds TaxRule objects keyed by country. A new market is a new or configured TaxRule registered at startup. The calculator class is final and contains no country names, so it never needs editing.

How is the open closed principle related to the strategy pattern?

The strategy pattern is one common way to apply it. The stable interface is the strategy, and each variant is a new implementation. The open closed principle is the goal; strategy, decorator, plugins and configuration tables are techniques that reach it.

Is the open closed principle the same as Protected Variations?

They are closely related; Craig Larman linked them in 2001. Protected Variations says to identify points of predicted variation and put a stable interface around them. Many readers find that wording clearer.

References

Exit mobile version