Chapter 18 of 26

SOLID: Single Responsibility & Open/Closed

Knowing classes, inheritance and polymorphism is like knowing how bricks, cement and steel work. It does not yet tell you how to design a building that will not crack when you add a new floor. SOLID is a set of five design principles that help you arrange classes so that the code stays easy to change as requirements grow.

In the Coupling & Cohesion chapter we learned that good designs have high cohesion and low coupling. The SOLID principles are practical rules for achieving exactly that. In this chapter we cover the first two letters, S and O.


What Is SOLID?

The principles were collected and popularized by Robert C. Martin ("Uncle Bob") around 2000, and Michael Feathers later arranged their initials into the acronym SOLID.

Letter

Principle

One-line idea

S

Single Responsibility Principle

A class should have one reason to change

O

Open/Closed Principle

Add new behavior by adding code, not by editing working code

L

Liskov Substitution Principle

Subclasses must be usable wherever the parent is expected

I

Interface Segregation Principle

Prefer small, focused interfaces over fat ones

D

Dependency Inversion Principle

Depend on abstractions, not on concrete details

L is covered in SOLID: Liskov Substitution Principle, and I and D in SOLID: Interface Segregation & Dependency Inversion.

One thing to keep in mind from the start: these are principles, not laws. They describe what tends to make code easier to change. Applying them blindly everywhere can make small programs needlessly complicated.


Single Responsibility Principle (SRP)

The common short form is:

A class should have only one reason to change.

"One reason to change" is easy to misread as "one method" or "do one tiny thing". Martin later clarified what he meant by tying it to people:

A module should be responsible to one, and only one, actor. An actor is a group of people (users or stakeholders) who would ask for a particular kind of change.

So the question to ask is not "how many methods does this class have?" but "how many different groups of people could ask me to change this class, for unrelated reasons?"

Why It Matters

When one class serves several actors, a change requested by one group can accidentally break something another group depends on. Several developers also end up editing the same file for unrelated reasons, causing merge conflicts. Splitting by responsibility keeps each change local.

Example: An Invoice That Does Too Much

import java.util.ArrayList;
import java.util.List;

// One class, three unrelated reasons to change
class Invoice {
    private final String customer;
    private final List<String> items = new ArrayList<>();
    private final List<Double> prices = new ArrayList<>();

    Invoice(String customer) { this.customer = customer; }

    void addItem(String item, double price) {
        items.add(item);
        prices.add(price);
    }

    // 1. Business rule: owned by the accounts team
    double total() {
        double sum = 0;
        for (double p : prices) sum += p;
        return sum * 1.18;   // 18% GST
    }

    // 2. Presentation: owned by whoever designs the bill layout
    String print() {
        StringBuilder sb = new StringBuilder("INVOICE for " + customer + "\n");
        for (int i = 0; i < items.size(); i++) {
            sb.append(String.format("  %-10s %8.2f%n", items.get(i), prices.get(i)));
        }
        sb.append(String.format("  %-10s %8.2f", "TOTAL", total()));
        return sb.toString();
    }

    // 3. Persistence: owned by the team that manages storage
    void saveToDatabase() {
        System.out.println("INSERT INTO invoices VALUES ('" + customer + "', " + total() + ")");
    }
}

public class InvoiceApp {
    public static void main(String[] args) {
        Invoice inv = new Invoice("Asha");
        inv.addItem("Keyboard", 1000);
        inv.addItem("Mouse", 500);
        System.out.println(inv.print());
        inv.saveToDatabase();
    }
}

Output:

INVOICE for Asha
  Keyboard    1000.00
  Mouse        500.00
  TOTAL       1770.00
INSERT INTO invoices VALUES ('Asha', 1770.0)

The program works. The problem is not correctness but change. Let us list who might ask for changes to this class:

Actor

Possible change request

Method affected

Accounts / tax team

"GST is now split into CGST and SGST" or "add a discount line"

total()

UI / design team

"Show the bill as HTML" or "add the company logo"

print()

Infrastructure team

"Move from MySQL to PostgreSQL" or "save to a REST service"

saveToDatabase()

Three actors, three reasons to change. The class has low cohesion: its methods are grouped together only because they all touch an invoice. Also note the hidden coupling: print() and saveToDatabase() both call total(), so a tax change could unexpectedly alter what gets stored.

Refactoring with SRP

We split the class so that each part answers to one actor:

import java.util.ArrayList;
import java.util.List;

record LineItem(String name, double price) { }

// Responsibility: invoice data and the business rules for the amount
class Invoice {
    private static final double GST_RATE = 0.18;

    private final String customer;
    private final List<LineItem> items = new ArrayList<>();

    Invoice(String customer) { this.customer = customer; }

    void addItem(String name, double price) { items.add(new LineItem(name, price)); }

    String customer() { return customer; }

    List<LineItem> items() { return List.copyOf(items); }

    double total() {
        double sum = 0;
        for (LineItem item : items) sum += item.price();
        return sum * (1 + GST_RATE);
    }
}

// Responsibility: how an invoice looks on paper or screen
class InvoicePrinter {
    String format(Invoice inv) {
        StringBuilder sb = new StringBuilder("INVOICE for " + inv.customer() + "\n");
        for (LineItem item : inv.items()) {
            sb.append(String.format("  %-10s %8.2f%n", item.name(), item.price()));
        }
        sb.append(String.format("  %-10s %8.2f", "TOTAL", inv.total()));
        return sb.toString();
    }
}

// Responsibility: where and how invoices are stored
class InvoiceRepository {
    void save(Invoice inv) {
        System.out.println("INSERT INTO invoices VALUES ('" + inv.customer() + "', " + inv.total() + ")");
    }
}

public class InvoiceApp {
    public static void main(String[] args) {
        Invoice inv = new Invoice("Asha");
        inv.addItem("Keyboard", 1000);
        inv.addItem("Mouse", 500);

        System.out.println(new InvoicePrinter().format(inv));
        new InvoiceRepository().save(inv);
    }
}

Output (unchanged behavior):

INVOICE for Asha
  Keyboard    1000.00
  Mouse        500.00
  TOTAL       1770.00
INSERT INTO invoices VALUES ('Asha', 1770.0)
            ┌───────────────────┐
            │      Invoice      │  ◀── tax / accounts team
            │ items, total()    │
            └─────────▲─────────┘
                      │ uses
        ┌─────────────┴──────────────┐
┌───────┴────────┐          ┌────────┴──────────┐
│ InvoicePrinter │          │ InvoiceRepository │
│ format()       │          │ save()            │
└────────────────┘          └───────────────────┘
  ▲ UI team                    ▲ infrastructure team

Now an HTML layout change touches only InvoicePrinter, a database change touches only InvoiceRepository, and a tax change touches only Invoice. Each class is small, easy to test and easy to understand.

(In real billing software you would use BigDecimal rather than double for money, to avoid rounding errors. We use double here to keep the example short.)

How to Spot an SRP Violation

  • The class description needs the word "and": "it calculates the total and prints it and saves it".

  • The class imports from very different areas: maths/business rules, formatting/UI and database/network all in one file.

  • Different methods use completely different subsets of the fields.

  • The class name is vague: InvoiceManager, Utils, Helper, Processor.

  • Unrelated features keep causing edits (and merge conflicts) in the same file.

Do Not Overdo It

SRP does not mean every class should have one method. Splitting total() into sumItems() and addTax() classes would scatter one responsibility (tax-inclusive amount calculation) across many places, which lowers cohesion. Things that change together for the same reason should stay together.


Open/Closed Principle (OCP)

Software entities (classes, modules, functions) should be open for extension but closed for modification.

  • Open for extension: you can make the module do new things.

  • Closed for modification: you can do that without editing its existing, tested source code.

This sounds contradictory at first. How can you change what code does without changing the code? The answer is abstraction and polymorphism, which we studied in the Abstraction and Polymorphism chapters: the stable code talks to an interface, and new behavior arrives as new classes that implement it.

A bit of history: the principle was first stated by Bertrand Meyer in 1988. His version suggested extending a class through inheritance. Robert Martin's later, now more common version uses interfaces / abstract types and polymorphism, so that new implementations can be plugged in without touching the code that uses them.

Example: A Discount Calculator

class DiscountCalculator {
    // Every new customer type means editing (and re-testing) this method
    double discount(String customerType, double amount) {
        if (customerType.equals("REGULAR")) {
            return 0;
        } else if (customerType.equals("PREMIUM")) {
            return amount * 0.10;
        } else if (customerType.equals("EMPLOYEE")) {
            return amount * 0.30;
        }
        throw new IllegalArgumentException("Unknown type: " + customerType);
    }
}

public class ShopBefore {
    public static void main(String[] args) {
        DiscountCalculator calc = new DiscountCalculator();
        System.out.println("PREMIUM  : " + calc.discount("PREMIUM", 2000));
        System.out.println("EMPLOYEE : " + calc.discount("EMPLOYEE", 2000));
    }
}

Output:

PREMIUM  : 200.0
EMPLOYEE : 600.0

Now the business says: "Add a student discount: 15%, capped at Rs 200." To support it, you must open DiscountCalculator and add another else if. Every new type means:

  • editing a class that already works (risk of breaking existing discounts),

  • re-testing all branches,

  • and the same if/else chain is often copied into other places (shipping cost, reward points ...), all of which must be found and edited.

A long if/else or switch on a type code is the classic OCP smell.

Refactoring with OCP

import java.util.List;

// The abstraction: closed for modification
interface DiscountPolicy {
    String name();
    double discount(double amount);
}

class RegularDiscount implements DiscountPolicy {
    public String name() { return "Regular"; }
    public double discount(double amount) { return 0; }
}

class PremiumDiscount implements DiscountPolicy {
    public String name() { return "Premium"; }
    public double discount(double amount) { return amount * 0.10; }
}

class EmployeeDiscount implements DiscountPolicy {
    public String name() { return "Employee"; }
    public double discount(double amount) { return amount * 0.30; }
}

// NEW requirement: students get 15%, capped at Rs 200.
// Added as a new class: no existing class was edited.
class StudentDiscount implements DiscountPolicy {
    public String name() { return "Student"; }
    public double discount(double amount) { return Math.min(amount * 0.15, 200); }
}

// Client code: depends only on the interface, never changes
class Checkout {
    double payable(double amount, DiscountPolicy policy) {
        return amount - policy.discount(amount);
    }
}

public class Shop {
    public static void main(String[] args) {
        Checkout checkout = new Checkout();
        List<DiscountPolicy> policies = List.of(
                new RegularDiscount(), new PremiumDiscount(),
                new EmployeeDiscount(), new StudentDiscount());

        for (DiscountPolicy p : policies) {
            System.out.printf("%-9s pays %7.2f on 2000%n", p.name(), checkout.payable(2000, p));
        }
    }
}

Output:

Regular   pays 2000.00 on 2000
Premium   pays 1800.00 on 2000
Employee  pays 1400.00 on 2000
Student   pays 1800.00 on 2000

Adding StudentDiscount required zero edits to DiscountPolicy, Checkout or the other policies. Checkout is closed for modification but open for extension: it will work with any future policy (festival sale, first-order offer ...). The only place that changes is where objects are created and wired together (here, main), which is normal and expected.

This interface-plus-implementations structure is essentially the Strategy pattern, which you will meet again in Behavioral Patterns: Observer, Strategy & Command.

Ways to Achieve OCP in Java

Technique

How it extends behavior

Interface + implementations

New class implements the interface (as above)

Abstract class + subclasses

New subclass overrides abstract or hook methods (Template Method pattern)

Passing behavior as a parameter

A lambda for a functional interface, e.g. list.sort(comparator): the sort method never changes, you pass new comparison logic

Composition / decorators

Wrap an object to add behavior (covered in the structural patterns chapter)

OCP Has Limits

No design is closed against every possible change. In our example, adding a new type of discount is easy, but if the business wants discounts that depend on the customer's purchase history, the discount(double) signature itself must change. Martin calls choosing which changes to protect against strategic closure.

A practical approach: write the simple version first. When the same kind of change happens a second or third time (a third else if for a new type), refactor to an abstraction. Adding interfaces "just in case" for changes that never come only adds complexity.


How SRP and OCP Work Together

Aspect

SRP

OCP

Main question

Who will ask for changes to this class?

Can I add new behavior without editing old code?

Main tool

Splitting classes by responsibility (actor)

Abstraction and polymorphism

Improves

Cohesion

Extensibility, lower coupling to concrete types

Typical smell

God class, "Manager" class, class described with "and"

Growing if/else or switch on a type code

They support each other: once responsibilities are separated (SRP), each part can be hidden behind an abstraction and extended independently (OCP). For instance, if we later need to save invoices to both MySQL and a cloud API, InvoiceRepository could become an interface with two implementations.


Common Mistakes

  • "SRP means one method per class." It means one reason to change, i.e. one actor. A class can have many methods that serve the same responsibility.

  • "OCP means you can never edit a class." Bug fixes are always allowed, and wiring/creation code must change when new classes are added. OCP is about not having to edit stable logic for every new variation.

  • Creating interfaces for everything up front. Abstractions that have only one implementation and no expected variation add indirection without benefit.

  • Replacing a switch but keeping it elsewhere. If the new policy classes are still chosen by a big switch sprinkled across the code, little is gained. Keep the selection in one place (for example a factory).


Interview Questions

State the Single Responsibility Principle. What is a "responsibility"?

A class should have only one reason to change. A responsibility is a reason to change, which Martin ties to an actor: a group of stakeholders who request a particular kind of change. A class should serve one actor.

Give an example of an SRP violation and how you would fix it.

An Invoice class that calculates the total, formats the printout and saves to the database serves the tax team, the UI team and the infrastructure team. Split it into Invoice (rules), InvoicePrinter (formatting) and InvoiceRepository (storage).

What does "open for extension, closed for modification" mean?

You should be able to add new behavior to a module (extend it) without changing its existing source code, usually by programming against an abstraction and adding new implementations.

A method has a switch on employee type to compute bonus. Which principle does it violate and how do you fix it?

The Open/Closed Principle: each new employee type requires editing the method. Fix it with polymorphism: an interface or abstract method bonus() implemented by each employee type (or a BonusPolicy strategy), so new types are new classes.

Who first stated OCP, and how does the modern version differ?

Bertrand Meyer (1988), who relied on extending classes through inheritance. Robert Martin's version relies on abstract interfaces and polymorphism, so implementations can be swapped and added freely.

Can a design be completely closed for modification?

No. You can only close it against the kinds of change you anticipate (strategic closure). Choose the abstractions based on changes that actually happen or are very likely.


Summary

  • SOLID = SRP, OCP, LSP, ISP, DIP: guidelines for code that is easy to change.

  • SRP: a class should have one reason to change, i.e. be responsible to one actor. It increases cohesion.

  • Spot SRP violations by the word "and", vague names like Manager/Utils, and unrelated edits to the same file.

  • OCP: extend behavior by adding new code (new implementations) instead of editing tested code.

  • Use interfaces, abstract classes and polymorphism to replace if/else chains on type codes.

  • Apply both principles where change is real or likely; avoid speculative abstractions.

OCP relies on substituting new implementations for an abstraction. But what if a subclass does not really behave like its parent? Then substitution breaks programs in subtle ways. That is the subject of the next chapter, SOLID: Liskov Substitution Principle.