SteelReed

Search

Search posts, questions…

3. Advanced Java

SOLID by problem: five ways to lower the cost of change, and when you don't need them

SOLID ordered by the problem each principle prevents: one change dragging in several groups (SRP by actor), adding a variant means editing running code (OCP, or sealed + switch), a new implementation silently breaking callers (Liskov, checked by contract tests), clients tied to methods they don't use (ISP), business rules tied to infrastructure (DIP vs DI); the cost of overdoing it and how to review designs an AI proposes.

19 Nov 20267 min readMid

–

1. The problem

Finance cuts the VIP discount from 10% to 8%. The PR edits BookingReportService, a class that computes money, formats CSV and sends mail. The author also reorders the columns, and the reconciliation job reads the wrong column for 2 days.

2. Key idea

Code is hard to change when things that change for different reasons are tied together.

Problem Symptom Principle
One class serves several groups git log mixes "fix discount" and "fix format" Single Responsibility
Adding a variant edits running code the same switch on type in many places Open/Closed
A new implementation silently breaks callers callers need instanceof on a subtype Liskov Substitution
Clients tied to methods they don't use mocking ten methods to test one Interface Segregation
Business rules tied to infrastructure testing a price rule needs a database Dependency Inversion

2.1 When to apply it, and when not?

Principle Use when Don't use when
S: split by actor tickets for the class come from two or more groups the parts always change together
O: extension point a second variant exists, a third is coming one variant only; for a closed set use sealed + switch
L: contract test an interface has two or more implementations, fakes included
I: role interfaces different clients use different parts the interface is already small, one client
D: interface on the business side database, mail, HTTP, clock boundaries pure logic inside one module

Rule of three: extract an extension point at the third variant.

2.2 Where do Liskov and DIP get misread?

  • Liskov: a subtype must not strengthen preconditions (reject input the parent accepts) or weaken postconditions (report success without doing it).
  • DIP is not DI: DIP says where the interface lives and who imports whom. DI is just wiring.

3. In Java

S, O and D usually come together.

JAVA
// O: a new customer type = a new class, RevenueCalculator unchanged
interface DiscountPolicy {
    boolean supports(CustomerType type);
    BigDecimal apply(BigDecimal amount);
}
 
// D: package booking.domain owns the interface; booking.infra.mail implements it
public interface ReportSender { void send(String to, String body); }
 
// S: one actor per class; the job only coordinates
final class DailyReportJob {
    private final RevenueCalculator calculator; // finance
    private final CsvFormatter formatter;       // operations
    private final ReportSender sender;          // infrastructure
    void run(List<Booking> bookings) {
        sender.send("[email protected]", formatter.format(calculator.net(bookings)));
    }
}
// VIP 2,000,000 -> 1,800,000; tests need no SMTP

Other languages: Go puts small interfaces on the consumer side; Python uses Protocol.

Polymorphism or sealed + switch?
Approach Easy to add Fits when
Interface + many classes new types open set: payment gateways, price rules
Sealed interface + switch new operations closed set: Success | Declined | Pending

With sealed types the compiler flags a switch missing a case, so you cannot forget a spot. That is not a dangerous "OCP violation".

4. Working with AI

Give the AI: listing the actor behind each method from git log, and writing contract tests.

Check in AI-written code:

  • Every new interface has at least two implementations, or is an infrastructure boundary.
  • No factory, Abstract… or I… wrapping a single class.
  • A typical change touches fewer files than before the split.
  • No subtype throws UnsupportedOperationException or "fakes success".

5. Exercises

Exercise 1: Two RateLimiter implementations from an AI

Contract RateLimiter { boolean tryAcquire(String key); }: each key gets at most limit true results; unknown keys are valid. The AI adds AlwaysAllow (always true, "for dev") and RegisteredOnly (throws on unregistered keys, "safer"). Which breaks Liskov, by which rule, and which test catches both?

Solution to Exercise 1

Both break it. AlwaysAllow weakens the postcondition (allows more than limit). RegisteredOnly strengthens the precondition (rejects unknown keys).

Catch both with a contract test: an abstract test class with createLimiter(int limit), one subclass per implementation. The test calls tryAcquire 10 times with limit 3 and calls it with an unknown key. If dev needs "always allow", configure a large limit instead of writing an implementation that lies about the contract.

Exercise 2: Incident after adding a customer type

The team adds STAFF to the CustomerType enum and all tests pass. At 02:00 the report job fails with IllegalStateException: no policy for STAFF; 312 STAFF bookings already exist. Diagnose, say what to do in 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: a variant was added to the enum without a matching DiscountPolicy bean. No test had a STAFF booking, so tests stayed green.
  • 15 minutes: deploy a STAFF policy (or no discount for now, if finance agrees) and rerun yesterday's job.
  • Root fix: check at startup that every CustomerType.values() has exactly one policy; add a parameterized test over all enum values. For a closed set, a switch without default lets the compiler catch a missing case.

Summary

  • Each principle stops one kind of change from spreading.
  • SRP is about actors, not "a class does one thing".
  • Liskov: no stronger preconditions, no weaker postconditions; check with contract tests.
  • DIP is the direction of dependencies, DI is wiring.
  • Drop any interface with no second variant that isn't an infrastructure boundary.

Read more: IoC and DI.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All OOP & Design questions →

Loading comments…
Next on the roadmapDesign patterns through refactoring: Strategy