← The Notebook

    Field Notes · Design

    SOLID Is One Idea Wearing Five Hats

    By Bakare Praise··10 min read

    Most of us meet SOLID as a quiz. Five letters, five definitions, recite them in an interview and move on. Then we go back to the codebase and dutifully perform them: an interface per class, a service per noun, a factory for something that will only ever be built one way. The letters get honoured and the code gets worse.

    The principles are not five rules. They are one question, asked from five directions: when the requirements change, and they will, how much of this has to move?

    Everything below is that question in a different costume.

    Single Responsibility: one reason to be edited

    The usual phrasing, "a class should do one thing," is useless, because "one thing" expands to fit whatever the class already does. Any method can be described as part of "handling orders" if you squint. The sharper version is Uncle Bob's own: a module should have one reason to change. And a reason to change is really a person who can demand it.

    I had an OrderService once that looked like this:

    @Service
    public class OrderService {
    
        public Order place(Cart cart, User user) {
            BigDecimal subtotal = cart.getItems().stream()
                    .map(i -> i.getPrice().multiply(BigDecimal.valueOf(i.getQuantity())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
    
            BigDecimal rate = "NG".equals(user.getRegion())
                    ? new BigDecimal("0.075")
                    : new BigDecimal("0.20");
            BigDecimal total = subtotal.add(subtotal.multiply(rate));
    
            Order order = jdbcTemplate.queryForObject(
                    "INSERT INTO orders (user_id, total) VALUES (?, ?) RETURNING *",
                    orderRowMapper, user.getId(), total);
    
            mailSender.send(user.getEmail(), "Your receipt", renderReceipt(order));
            return order;
        }
    }
    

    Four responsibilities, but more importantly four stakeholders: the finance team owns the totals, the tax regime owns the rate, the DBA owns the schema, marketing owns the email. Any of them could walk in on any Monday and force a change to the same file, and none of them care about the other three.

    The symptom was visible in git before it was visible in the code. That file was in nearly every pull request, and the diffs had nothing to do with each other. When a VAT change and a receipt redesign land in the same file in the same sprint, you get merge conflicts between people who have never spoken.

    Split it into a PricingPolicy, an OrderRepository, a ReceiptNotifier and a thin service that sequences them, and each stakeholder gets their own door. Tax rules change; the mailer is not recompiled, not retested, not at risk. The test for pricing stops needing a database.

    A practical detector, no theory required: open the file's history. If the last ten commits touching it have ten unrelated messages, it has ten reasons to change.

    Open–Closed: the switch that grows forever

    Every payment integration starts honestly.

    if (provider.equals("paystack")) return chargePaystack(request);
    if (provider.equals("flutterwave")) return chargeFlutterwave(request);
    

    Six months later that block is eleven branches long. Worse, it has bred: the same branch appears in refund(), in verifyWebhook(), in the reconciliation job, in a reporting query. Adding a provider means finding all four sites, and the one you miss is the one that silently drops refunds for the newest provider.

    Adding behaviour should mean adding code, not editing code that already works:

    public interface PaymentProvider {
        String name();
        ChargeResult charge(ChargeRequest request);
        RefundResult refund(String reference);
        boolean verifyWebhook(String rawBody, String signature);
    }
    
    @Service
    public class PaymentRouter {
    
        private final Map<String, PaymentProvider> providers;
    
        public PaymentRouter(List<PaymentProvider> providers) {
            this.providers = providers.stream()
                    .collect(toMap(PaymentProvider::name, identity()));
        }
    
        public ChargeResult charge(String name, ChargeRequest request) {
            PaymentProvider provider = providers.get(name);
            if (provider == null) throw new UnknownProviderException(name);
            return provider.charge(request);
        }
    }
    

    A new provider is now one new class annotated @Component; Spring collects it into that injected List and the router never learns its name. The router, and its tests, do not move at all. Note what the interface did that the if chain never could: it made the full contract explicit. You cannot add a provider and forget refunds, because the compiler will not let you.

    Two things worth saying out loud, because the principle is usually taught without them.

    The dispatch does not disappear; it moves. Something, somewhere, still maps a string to an implementation. Open–Closed does not delete that decision; it isolates it to one place that changes in a predictable, additive way, instead of scattering it across the code that does the real work.

    Doing this on day one is not Open–Closed. For a system with exactly one provider and no evidence of a second, it is a plugin architecture for a single plugin. You will guess the seam wrong, because the first implementation's shape is indistinguishable from the general shape until a second one disagrees with it. Wait for the second case. The second case is what tells you where the seam actually is, and if the second case never comes, the if was right all along.

    Liskov: the subtype that lies

    Liskov is the one people skip because it sounds academic, and it is the one that produces the ugliest production bugs. It says a subtype must be usable anywhere its parent is, without the caller knowing which one it got.

    The violation is rarely a compiler error:

    public class ReadOnlyUserRepository implements UserRepository {
    
        @Override
        public Optional<User> findById(String id) {
            return delegate.findById(id);
        }
    
        @Override
        public User save(User user) {
            throw new UnsupportedOperationException("read-only repository");
        }
    }
    

    Every signature matches. It compiles, and javac has no complaint to make, in the same way that Collections.unmodifiableList hands you something that is a List right up until you call add() on it. And every caller written against UserRepository now has a runtime landmine under it that no test of this class will find, because the class tests assert the throw.

    It takes quieter forms, too, and they are worse because nothing throws at all:

    • A CachedUserStore that returns stale rows where the interface promised current ones. The caller reads a balance that was true ninety seconds ago and makes a decision with it.
    • An override that narrows what it accepts: the parent takes any string, while the child rejects anything over 64 characters. Callers that were correct against the parent start failing against the child.
    • A test double that succeeds where the real implementation would have rejected. The suite is green, the contract was never exercised, and production disagrees.

    The pattern is the same each time: the type system checks shape, and Liskov is about behaviour. The compiler will never catch it for you.

    Inheritance is a promise about behaviour, not a shortcut for sharing code. Break the promise and the caller has no way to know.

    The fix is usually to stop lying with the type. If a thing cannot save, it does not implement a UserRepository. It implements a UserReader, and the callers that need writes ask for a UserWriter and get one. Let the compiler enforce at the seam what you were about to enforce with an exception at runtime.

    The best test of a Liskov violation is to run the same suite against every implementation of the interface. If a contract test passes for one implementation and fails for another, you have found the lie before a caller does.

    Interface Segregation: don't make callers carry what they don't use

    A twenty-method NotificationService that every consumer must implement in full is a coupling machine. Adding sendWhatsApp() breaks six implementations that had no interest in WhatsApp, and each one grows another stub that throws, which is a Liskov violation you manufactured yourself by way of a fat interface.

    public interface Notifier {
        void send(Recipient to, Message message);
    }
    
    public interface RetryPolicy {
        boolean shouldRetry(int attempt, Exception error);
    }
    

    A class implements what it actually does. A caller depends on the one verb it needs, so a caller that only sends is not recompiled, not retested, and not affected when the retry policy gains a method.

    The same idea reaches past classes. A REST endpoint that returns a forty-field user object to a client that renders a name and an avatar is the same failure at the network boundary: the consumer is coupled to thirty-eight fields it never reads, and any one of them changing is a breaking change it has to care about.

    This is Single Responsibility seen from the caller's side rather than the owner's. It is the same question, how much has to move, from a different angle.

    Dependency Inversion: point at ideas, not instruments

    The rule I actually use: high-level policy should not import low-level detail. Business logic should not import javax.sql.DataSource, and it should not know that jakarta.persistence exists.

    The direction of the arrow is the whole principle, and the giveaway is which package owns the interface. Not this:

    package com.example.domain;
    
    import com.example.infrastructure.PostgresUserRepository;
    
    public class RegisterUser {
        private final PostgresUserRepository users = new PostgresUserRepository();
    }
    

    But this, where the domain declares the interface it needs and the Postgres class is the one doing the depending:

    package com.example.domain;
    
    public interface UserRepository {
        Optional<User> findByEmail(String email);
        User save(User user);
    }
    
    public class RegisterUser {
    
        private final UserRepository users;
    
        public RegisterUser(UserRepository users) {
            this.users = users;
        }
    }
    

    com.example.domain now imports nothing from com.example.infrastructure, and that is a rule you can enforce in the build with ArchUnit rather than in code review, where it will be forgotten. Both the policy and the driver point at the same abstraction, and the abstraction lives with the policy, because the policy is what defines what it needs. That last part is what people miss: an interface that lives next to its single implementation, in the infrastructure package, has inverted nothing. You have written the same dependency with an extra file, and that is most of what UserServiceImpl sitting beside UserService in the same package has ever bought anyone.

    The payoff is not swapping databases. You almost never will, and "we might move to Mongo" is the weakest argument for this principle. The real returns are more ordinary:

    • Domain logic becomes testable in milliseconds, with an in-memory fake that is nothing more than a HashMap behind the interface. No @SpringBootTest, no Testcontainers, no truncating tables between runs. The unit tests that matter stop waiting on a context to start.
    • The day you move from a hand-rolled queue to RabbitMQ, the change is confined to one adapter instead of scattered through the code that matters most.
    • The domain reads as business rules rather than SQL, so someone new can follow what the system does before learning where it stores things.

    Spring makes this cheap enough that there is little excuse: the interface is yours, the implementation carries @Repository, and constructor injection wires them without the policy ever naming the driver. The framework's whole job is to be the thing that knows about both, so that nothing in your domain has to.

    One question, five angles

    Read them together and they stop being a checklist:

    • Single Responsibility keeps reasons to change from piling into one file.
    • Open–Closed keeps change from touching working code.
    • Liskov keeps change from breaking callers that trusted a contract.
    • Interface Segregation keeps change from reaching code that does not care.
    • Dependency Inversion keeps change in the details from reaching the policy.

    Every one of them is about containing the blast radius of a change. That is the whole idea. The five letters are just five places it tends to escape from. They also overlap constantly, which is the tell that they were never independent. Fat interfaces force stub methods that throw, so Interface Segregation failures become Liskov failures. A class with four responsibilities has four reasons to be edited, so Single Responsibility failures become Open–Closed failures. You rarely fix one in isolation.

    Which also means SOLID has a cost, and the cost is paid in indirection: more files, more names, more hops between the line you are reading and the line that does the work. A junior engineer chasing a bug through six interfaces to find the one class that does anything is paying that cost, and they did not get a vote. Applied to code that genuinely changes, the cost buys you calm. Applied on principle, to code nobody has touched in a year, it buys you a maze.

    So the honest heuristic is not "follow SOLID." It is: find where change actually lands and spend your indirection there. Those are the files in every pull request, the ones with the longest git history, the ones people are afraid of. The rest of the codebase can stay boring.


    ← All notes

    Also in the notebook


    Colophon

    "I invented the term object-oriented, and I can tell you I did not have C++ in mind."
    — Alan Kay

    Print Run

    Three years in circulation across fintech, logistics, med-tech, ed-tech and e-commerce. Readership measured in uptime, not clicks — a new edition ships whenever the backend does.

    Office

    England, United Kingdom.
    [email protected]


    © 2026 Bakare Praise Stephen. All rights reserved.
    Visits are logged with approximate location and time. IP addresses are not stored.

    Vol. I · No. 1 · Filed from England

    Return to the masthead ↑