Skip to main content
OOP and design · Topic 8 of 12

Single responsibility

Definition​

The single responsibility principle says a class should have one reason to change. Each class does one job, so a change to one concern does not break another.

Example code​

Calculating an invoice and printing it are two jobs

import java.util.List;

record Item(String name, int price) { }

class Invoice { // job 1: know the items and the total
private final List<Item> items;
Invoice(List<Item> items) { this.items = items; }
List<Item> items() { return items; }
int total() { return items.stream().mapToInt(Item::price).sum(); }
}

class InvoicePrinter { // job 2: format the invoice as text
String print(Invoice invoice) {
StringBuilder out = new StringBuilder();
for (Item item : invoice.items()) out.append(item.name()).append(": ").append(item.price()).append('\n');
return out.append("Total: ").append(invoice.total()).toString();
}
}

class Demo {
public static void main(String[] args) {
Invoice invoice = new Invoice(List.of(new Item("Book", 300), new Item("Pen", 20)));
System.out.println(new InvoicePrinter().print(invoice)); // changing the format never touches Invoice
}
}

// Output:
// Book: 300
// Pen: 20
// Total: 320

Finished this page? Track your progress (saved only in your browser).