SOLID and responsibility
What you will learn
SOLID describes five ways to manage change in object-oriented designs. Start with a behavior you can test, identify the responsibility that changes, and introduce a boundary only when it makes the change easier to understand or verify.
- Preserve outputs while separating calculation from formatting.
- Use narrow interfaces and substitute implementations without breaking their contracts.
- Explain dependency direction and the cost of unnecessary abstraction.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. All examples in this chapter are standalone, single-threaded Java 21 models unless stated otherwise.
Before and after: reservation receipt
public class Main { static String before(int n) { return "Total: " + Math.multiplyExact(n, 250); } static int total(int n) { return Math.multiplyExact(n, 250); } static String render(int cents) { return "Total: " + cents; } public static void main(String[] args) { for (int n : new int[]{0, 1, 4}) { String old = before(n); String updated = render(total(n)); if (!old.equals(updated)) throw new AssertionError(n); System.out.println(updated); } }}Expected output:
Total: 0Total: 250Total: 1000The same cents calculation now has a separate formatting function. The equality check covers three representative inputs; it is not a proof about every input. A new output format need not edit total().
Responsibility, cohesion and coupling
Cohesion is how closely the work inside a component belongs together; coupling is the knowledge one component needs about another. Single responsibility (SRP) asks which stakeholder or change pressure drives a component. A calculation and a display format may change independently. Splitting them is useful if it makes each rule easier to test; a single method is not automatically a single responsibility.
The remaining four SOLID heuristics
Open/closed (OCP): accommodate a known variation without editing stable policy each time; it does not prohibit changes. Liskov substitution (LSP): a replacement must honor the observable contract, including accepted inputs, results and failure behavior. Interface segregation (ISP): clients should depend on the operations they actually need. Dependency inversion (DIP): policy defines the abstraction it needs, while infrastructure implements it. Constructor injection is one mechanism for providing that implementation, not the principle itself.
Refactor under a behavioral test
Capture output and boundary behavior first. Move the calculation without changing its rule. Run the same inputs afterward, including zero, negative and overflow boundaries where relevant. Separate a behavior change into a later commit. Passing examples give limited regression evidence, not proof of universal equivalence.
A policy depends on its own narrow port
public class Main { interface StockReader { int available(String sku); } static boolean canReserve(StockReader stock, String sku, int n) { if (n <= 0) throw new IllegalArgumentException("quantity"); return stock.available(sku) >= n; } public static void main(String[] args) { StockReader reader = sku -> sku.equals("pen") ? 4 : 0; System.out.println(canReserve(reader, "pen", 3)); System.out.println(canReserve(reader, "pen", 5)); System.out.println(canReserve(reader, "missing", 1)); }}Expected output:
truefalsefalsePolicy calls a read-only operation. The lambda is a test substitute, not a real database. A read followed by a reservation would need atomic consistency; this check alone cannot prevent overselling.
Substitution checks for two implementations
public class Main { interface Counter { void add(int n); int value(); } static int next(int old, int n) { if (n < 0) throw new IllegalArgumentException("negative"); return Math.addExact(old, n); } static class MutableCounter implements Counter { int count; public void add(int n) { count = next(count,n); } public int value() { return count; } } static class ArrayCounter implements Counter { final int[] cell = {0}; public void add(int n) { cell[0] = next(cell[0],n); } public int value() { return cell[0]; } } public static void main(String[] args) { for (Counter c : java.util.List.of(new MutableCounter(), new ArrayCounter())) { c.add(2); c.add(3); if (c.value() != 5) throw new AssertionError(); try { c.add(-1); throw new AssertionError(); } catch (IllegalArgumentException expected) { } System.out.println(c.value()); } }}Expected output:
55Both implementations start at zero, reject negative increments without mutation, and produce the same result for the contract test. A subtype that silently accepted negative values would violate this contract. The array implementation is intentionally artificial to show substitutability, not a recommended design.
Common mistakes
Do not create an interface for every class by default. Avoid splitting cohesive behavior into tiny objects that require constant navigation. Do not claim substitutability just because code compiles; define and test the contract.
Practice
Separate delivery-fee calculation from receipt rendering. Use a fixed 300-cent fee for positive quantities and zero for zero; reject negative quantities. Test 0 and 2.
Expected output:
Fee: 0Fee: 300rejectedCompare with the manual review criteria.
Further reading: SOLID. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
SOLID and responsibility — knowledge check
Design and domain modeling reasoning.
Which change pressure suggests separating receipt calculation and display?
Which property matters for Liskov substitution?
Which dependency direction fits DIP?
Which interface best serves a read-only stock client?
When is an interface unnecessary?