OOP in Practice · Episode 7 of 70 · SOLID Principles · Beginner · PHP 8.3.6
The problem
You maintain the billing code for a small hosting company, and its Invoice class breaks the single responsibility principle. That one class adds up lines, applies 18% tax, builds the document, emails the customer and writes to MySQL. Finance wants a new tax rate, design wants a new layout, and ops wants a new mail provider, all this month. Every change lands in the same file.
Your task: refactor the Invoice class so each reason to change lives in its own class, without changing the numbers it produces.
Requirements
- An invoice has a number, a customer email and one or more line items.
- Tax is a configurable rate, rounded half up to the nearest paisa.
- The invoice is rendered to a document; the format can be swapped.
- Issuing an invoice saves it, then emails the document.
- Reject a zero quantity, a blank description, an empty invoice and a duplicate invoice number.
Constraints and assumptions
- Single process, in memory. The database and mail server are replaced by fakes behind interfaces.
- Money is stored as integer paise (1 rupee = 100 paise). Example rates only; this is not tax advice.
What this tests: single responsibility, cohesion, encapsulation, interfaces, dependency injection
The single responsibility principle says a class should have one reason to change. Split the invoice by who asks for changes: Invoice and LineItem hold data, TaxCalculator owns the tax rule, a renderer owns layout, a repository owns storage, a mailer owns delivery, and a small IssueInvoice class only sequences the steps.
Try it yourself first — hint
For each method, write down which team would ask you to change it. Methods with the same answer stay together.
Step 1: Identify the objects and responsibilities
In his 2014 article, Martin says the reasons to change are the people who request changes. So list the actors first: finance, design, the data team and ops.
| Class / interface | Responsibility | Key methods |
|---|---|---|
LineItem |
One immutable billed line; rejects bad input. Changes when the shape of a line changes. | amountCents() |
Invoice |
Number, email and lines; the subtotal. Changes when billing data changes. | add(), lines(), subtotalCents() |
TaxCalculator |
The tax rule and its rounding. Changes when finance changes the rule. | taxCents() |
InvoiceRenderer (interface) |
Turns an invoice into a document. Changes when design changes the layout. | render() |
InvoiceRepository (interface) |
Stores issued invoices; blocks duplicate numbers. Changes when storage changes. | save() |
Mailer (interface) |
Delivers a message. Changes when ops switches provider. | send() |
IssueInvoice |
Runs the steps in order. Changes only when the issuing workflow changes. | __invoke() |
Step 2: The naive approach and why it breaks
<?php
declare(strict_types=1);
class Invoice
{
public array $lines = [];
public function __construct(public string $number, public string $email) {}
public function addLine(string $desc, float $price, int $qty): void
{
$this->lines[] = [$desc, $price, $qty];
}
public function total(): float // finance owns this rule
{
$sum = 0.0;
foreach ($this->lines as [$d, $p, $q]) { $sum += $p * $q; }
return $sum * 1.18; // tax rate hard-coded
}
public function toHtml(): string { /* layout: design team */ return "<h1>{$this->number}</h1><p>" . $this->total() . "</p>"; }
public function email(): void { /* SMTP: ops team */ mail($this->email, "Invoice", $this->toHtml()); }
public function save(): void { /* SQL: data team */ (new PDO('mysql:host=db'))->exec("INSERT ..."); }
}
Run with the same two lines used later, then with one quantity set to zero from outside, it printed:
<h1>INV-1001</h1><p>8127.8282</p> 1061.9882
- Four teams, one file. Tax, layout and mail changes all edit
Invoice, and each risks the others. - Untestable side effects. You cannot exercise
email()orsave()in a unit test without a mail server and a MySQL host, because the class creates them itself. - Float money. The document shows
8127.8282, not a rupee amount. The PHP manual warns that floats have limited precision, so money should not be stored in them. - No guard on data. The public
$linesarray let outside code set a quantity to 0, and the total silently dropped to 1061.9882.
Step 3: The design
+------------------------------+
| IssueInvoice (coordinator) |
| __invoke(Invoice): string |
+------------------------------+
| | | |
+----------+ +----+ +---+ +-------------+
v v v v
+---------------+ +-----------------+ +-------------------+ +---------------+
| TaxCalculator | | <<interface>> | | <<interface>> | | <<interface>> |
| taxCents() | | InvoiceRenderer | | InvoiceRepository | | Mailer |
+---------------+ +-----------------+ +-------------------+ +---------------+
| ^ ^ ^
| reads | implements | implements | implements
v TextInvoiceRenderer InMemoryInvoiceRepo FakeMailer
+-------------------+
| Invoice | 1 * +-------------------------------+
| number, email |<>-------->| LineItem (readonly) |
| add(), lines() | | description, unitCents, qty |
| subtotalCents() | | amountCents() |
+-------------------+ +-------------------------------+
Martin’s rule: gather together the things that change for the same reasons, and separate those that change for different reasons. That gives four groups: data, tax, presentation, and delivery or storage.
The data classes reuse encapsulation: LineItem validates itself and cannot be edited after it is built. Rendering, storage and mail sit behind interfaces, so IssueInvoice depends on what they do, not on SMTP or SQL. That idea gets its own episode as the dependency inversion principle.
Step 4: The single responsibility principle solution in PHP
<?php
declare(strict_types=1);
// ── Data: what an invoice IS ───────────────────────────────────────
final class LineItem
{
public function __construct(
public readonly string $description,
public readonly int $unitCents, // money as integer paise, never float
public readonly int $quantity,
) {
if (trim($description) === '') throw new InvalidArgumentException('description is blank');
if ($unitCents < 0) throw new InvalidArgumentException('price is negative');
if ($quantity < 1) throw new InvalidArgumentException("quantity must be >= 1, got $quantity");
}
public function amountCents(): int { return $this->unitCents * $this->quantity; }
}
final class Invoice
{
/** @var list<LineItem> */
private array $lines = [];
public function __construct(public readonly string $number, public readonly string $customerEmail) {}
public function add(LineItem $line): self { $this->lines[] = $line; return $this; }
/** @return list<LineItem> */
public function lines(): array { return $this->lines; } // arrays are copied on return
public function subtotalCents(): int
{
return array_sum(array_map(fn(LineItem $l) => $l->amountCents(), $this->lines));
}
}
// ── Finance: how much it COSTS ─────────────────────────────────────
final class TaxCalculator
{
public function __construct(private readonly int $rateBasisPoints) {} // 1800 = 18%
public function taxCents(Invoice $invoice): int // rounds half up to the nearest paisa
{
return intdiv($invoice->subtotalCents() * $this->rateBasisPoints + 5000, 10000);
}
}
// ── Presentation: how it LOOKS ─────────────────────────────────────
interface InvoiceRenderer { public function render(Invoice $invoice, int $taxCents): string; }
final class TextInvoiceRenderer implements InvoiceRenderer
{
public function render(Invoice $invoice, int $taxCents): string
{
$out = "INVOICE {$invoice->number}\n";
foreach ($invoice->lines() as $l) {
$out .= sprintf(" %-14s %2d x %9s = %11s\n", $l->description, $l->quantity,
Money::format($l->unitCents), Money::format($l->amountCents()));
}
$sub = $invoice->subtotalCents();
return $out . sprintf(" %-31s %11s\n %-31s %11s\n %-31s %11s", 'Subtotal', Money::format($sub),
'Tax', Money::format($taxCents), 'Total', Money::format($sub + $taxCents));
}
}
final class Money
{
public static function format(int $cents): string { return 'Rs ' . number_format($cents / 100, 2); }
}
// ── Delivery and storage: where it GOES ────────────────────────────
interface Mailer { public function send(string $to, string $subject, string $body): void; }
final class FakeMailer implements Mailer // a real one would wrap SMTP or an email API
{
/** @var list<string> */
public array $sent = [];
public function send(string $to, string $subject, string $body): void { $this->sent[] = "$to | $subject"; }
}
interface InvoiceRepository { public function save(Invoice $invoice, int $totalCents): void; }
final class InMemoryInvoiceRepository implements InvoiceRepository
{
/** @var array<string, int> */
private array $rows = [];
public function save(Invoice $invoice, int $totalCents): void
{
if (isset($this->rows[$invoice->number])) throw new DomainException("invoice {$invoice->number} already saved");
$this->rows[$invoice->number] = $totalCents;
}
public function count(): int { return count($this->rows); }
}
// ── Coordination: the order of steps, and nothing else ─────────────
final class IssueInvoice
{
public function __construct(private TaxCalculator $tax, private InvoiceRenderer $renderer,
private InvoiceRepository $repo, private Mailer $mailer) {}
public function __invoke(Invoice $invoice): string
{
if ($invoice->lines() === []) throw new DomainException("invoice {$invoice->number} has no lines");
$taxCents = $this->tax->taxCents($invoice);
$document = $this->renderer->render($invoice, $taxCents);
$this->repo->save($invoice, $invoice->subtotalCents() + $taxCents); // save first, then email
$this->mailer->send($invoice->customerEmail, "Invoice {$invoice->number}", $document);
return $document;
}
}
// ── Demo ───────────────────────────────────────────────────────────
$repo = new InMemoryInvoiceRepository();
$mailer = new FakeMailer();
$issue = new IssueInvoice(new TaxCalculator(1800), new TextInvoiceRenderer(), $repo, $mailer);
$inv = (new Invoice('INV-1001', 'asha@example.com'))
->add(new LineItem('Web hosting', 49900, 12))
->add(new LineItem('Domain', 89999, 1));
echo $issue($inv), "\n";
echo "Mailed: {$mailer->sent[0]}\n\n";
echo "Same invoice data at 5%: ",
Money::format((new TaxCalculator(500))->taxCents($inv)), " tax (only TaxCalculator changed)\n";
$checks = [
'zero quantity' => fn() => new LineItem('Support', 1000, 0),
'blank description' => fn() => new LineItem(' ', 1000, 1),
'empty invoice' => fn() => $issue(new Invoice('INV-1002', 'raj@example.com')),
'duplicate number' => fn() => $issue($inv),
'edit a line item' => fn() => $inv->lines()[0]->quantity = 99,
];
foreach ($checks as $name => $attempt) {
try { $attempt(); echo "$name: accepted (bug!)\n"; }
catch (Throwable $e) { echo str_pad($name, 18), '-> ', get_class($e), ': ', $e->getMessage(), "\n"; }
}
echo "Saved invoices: {$repo->count()}, emails sent: " . count($mailer->sent) . "\n";
- Readonly data. Readonly properties (PHP 8.1+) can be set once, from inside the class. Writing one later throws an
Error, which the demo shows. Constructor promotion (PHP 8.0+) declares and assigns them in one line. - Integer paise. Tax is
subtotal × basis points / 10,000with+5000added first, sointdiv()rounds half up for positive amounts. 18% of Rs 6,887.99 is Rs 1,239.838, billed as Rs 1,239.84. - No leaking array.
lines()returns the array, and PHP copies arrays on assignment, so a caller can append to its copy without touching the invoice. - Interfaces at the edges. A class that implements an interface must provide every method in it. So
FakeMailerand a real SMTP mailer are swappable, and tests never send email. - Save before send. The duplicate check runs before the email, so a rejected invoice never reaches the customer: one save, one email.
Step 5: Run it and check the output
INVOICE INV-1001 Web hosting 12 x Rs 499.00 = Rs 5,988.00 Domain 1 x Rs 899.99 = Rs 899.99 Subtotal Rs 6,887.99 Tax Rs 1,239.84 Total Rs 8,127.83 Mailed: asha@example.com | Invoice INV-1001 Same invoice data at 5%: Rs 344.40 tax (only TaxCalculator changed) zero quantity -> InvalidArgumentException: quantity must be >= 1, got 0 blank description -> InvalidArgumentException: description is blank empty invoice -> DomainException: invoice INV-1002 has no lines duplicate number -> DomainException: invoice INV-1001 already saved edit a line item -> Error: Cannot modify readonly property LineItem::$quantity Saved invoices: 1, emails sent: 1
Tested: PHP 8.3.6 (cli) — php main.php, 2026-11-24. Output above is copied from that run.
Why this design works
- One actor per class. Finance edits
TaxCalculatorand nothing else. The 5% line in the output came from swapping one constructor argument. - Cohesion. Each class holds only things that change together.
- Encapsulation. Data classes enforce their own rules, so no caller can build a zero-quantity line.
- Open for extension. A new format is a new
InvoiceRendererclass; existing classes stay untouched. That is the open/closed principle, which builds on this one.
Trade-offs, edge cases and when not to use it
| Option | Good when | Cost |
|---|---|---|
One Invoice class doing everything |
A throwaway script with one owner and no tests | Every change touches every feature; needs real SMTP and DB to test |
| Split by actor (this episode) | Several teams or rules change at different speeds | Seven types instead of one; a reader must follow the coordinator |
| Split by method (a class per verb) | Rarely; only if each verb has its own owner | Over-fragmented: one idea spread across many tiny files |
One edge case stays open: if email fails after the save, the invoice is stored but not delivered (Practice 3). For a short script with one owner, the split is overkill. My recommendation: split when a second actor shows up, not before.
Interview follow-up questions
Isn’t IssueInvoice now a class that does everything?
No. It knows the order of the steps and nothing about how each step works. It holds no tax rate, no layout and no SQL. Its only reason to change is the workflow itself, such as “save before sending”. If it grew branches for every customer type, a policy object would be missing.
How would you add a PDF version and a second tax rule for exports?
Add a PdfInvoiceRenderer that implements InvoiceRenderer and pass it to IssueInvoice. No existing class changes. For exports, make TaxCalculator an interface with two implementations, or keep one class and pass a zero rate. Choosing between interchangeable rules at run time is the Strategy pattern, covered next.
How would you test this, and what if email fails after the save?
Unit-test TaxCalculator and LineItem directly; they have no dependencies. Test IssueInvoice with the in-memory repository and fake mailer, and assert what each one received. For failure, record “issued but not sent” and retry later, instead of rolling back a valid invoice.
The same solution in Python
Show the Python version
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Protocol
@dataclass(frozen=True)
class LineItem:
description: str
unit_cents: int
quantity: int
def __post_init__(self) -> None:
if not self.description.strip():
raise ValueError("description is blank")
if self.unit_cents < 0 or self.quantity < 1:
raise ValueError(f"bad price/quantity: {self.unit_cents}, {self.quantity}")
@property
def amount_cents(self) -> int:
return self.unit_cents * self.quantity
@dataclass
class Invoice:
number: str
customer_email: str
lines: list[LineItem] = field(default_factory=list)
def subtotal_cents(self) -> int:
return sum(line.amount_cents for line in self.lines)
class TaxCalculator:
def __init__(self, rate_basis_points: int) -> None:
self._bp = rate_basis_points
def tax_cents(self, invoice: Invoice) -> int:
return (invoice.subtotal_cents() * self._bp + 5000) // 10000
def money(cents: int) -> str:
return f"Rs {cents / 100:,.2f}"
class InvoiceRenderer(Protocol):
def render(self, invoice: Invoice, tax_cents: int) -> str: ...
class TextInvoiceRenderer:
def render(self, invoice: Invoice, tax_cents: int) -> str:
rows = [f"INVOICE {invoice.number}"]
rows += [f" {l.description:<14} {l.quantity:>2} x {money(l.unit_cents):>9} = {money(l.amount_cents):>11}"
for l in invoice.lines]
sub = invoice.subtotal_cents()
for label, cents in (("Subtotal", sub), ("Tax", tax_cents), ("Total", sub + tax_cents)):
rows.append(f" {label:<31} {money(cents):>11}")
return "\n".join(rows)
class Mailer(Protocol):
def send(self, to: str, subject: str, body: str) -> None: ...
class FakeMailer:
def __init__(self) -> None:
self.sent: list[str] = []
def send(self, to: str, subject: str, body: str) -> None:
self.sent.append(f"{to} | {subject}")
class InMemoryInvoiceRepository:
def __init__(self) -> None:
self._rows: dict[str, int] = {}
def save(self, invoice: Invoice, total_cents: int) -> None:
if invoice.number in self._rows:
raise LookupError(f"invoice {invoice.number} already saved")
self._rows[invoice.number] = total_cents
class IssueInvoice:
def __init__(self, tax: TaxCalculator, renderer: InvoiceRenderer,
repo: InMemoryInvoiceRepository, mailer: Mailer) -> None:
self._tax, self._renderer, self._repo, self._mailer = tax, renderer, repo, mailer
def __call__(self, invoice: Invoice) -> str:
if not invoice.lines:
raise ValueError(f"invoice {invoice.number} has no lines")
tax = self._tax.tax_cents(invoice)
document = self._renderer.render(invoice, tax)
self._repo.save(invoice, invoice.subtotal_cents() + tax)
self._mailer.send(invoice.customer_email, f"Invoice {invoice.number}", document)
return document
if __name__ == "__main__":
mailer = FakeMailer()
issue = IssueInvoice(TaxCalculator(1800), TextInvoiceRenderer(), InMemoryInvoiceRepository(), mailer)
inv = Invoice("INV-1001", "asha@example.com",
[LineItem("Web hosting", 49900, 12), LineItem("Domain", 89999, 1)])
print(issue(inv))
print(f"Mailed: {mailer.sent[0]}")
try:
issue(inv)
except LookupError as e:
print(f"duplicate number -> {e}")
INVOICE INV-1001 Web hosting 12 x Rs 499.00 = Rs 5,988.00 Domain 1 x Rs 899.99 = Rs 899.99 Subtotal Rs 6,887.99 Tax Rs 1,239.84 Total Rs 8,127.83 Mailed: asha@example.com | Invoice INV-1001 duplicate number -> invoice INV-1001 already saved
Python 3.13.18 uses a frozen dataclass for LineItem and Protocol classes in place of interfaces.
Practice: extend it yourself
- Add an
HtmlInvoiceRenderer. Escape the description so a line named<b>prints as text. Expected behaviour:TaxCalculator,InvoiceandIssueInvoicestay unchanged, and the total is still Rs 8,127.83. - Add a discount: 10% off lines with quantity 12 or more, applied before tax. Put the rule in its own class. Expected behaviour: hosting becomes Rs 5,389.20; no change to the renderer or mailer.
- Make
FakeMailerable to throw. Expected behaviour: the invoice is still saved,IssueInvoicereports it as “saved, not sent”, and issuing it again is still rejected as a duplicate.
- The single responsibility principle says a class should have only one reason to change.
- A “reason to change” is a person or team who asks for changes, not a method or a feature.
- Split an invoice into data, tax, rendering, storage, delivery and a coordinator that only sequences steps.
- SRP is a form of cohesion: keep together what changes together, separate what changes for different reasons.
- Store money as integer minor units such as paise, and round in one place.
Frequently Asked Questions
What is the single responsibility principle?
It is the S in SOLID. Robert C. Martin states it as: a class should have only one reason to change. His later wording says a module should be responsible to one actor, meaning one group of people who ask for changes. Code that changes for different people's reasons belongs in different classes.
Does the single responsibility principle mean a class should have only one method?
No. A class can have many methods if they all serve the same actor. Invoice in this episode has add(), lines() and subtotalCents() and still has one reason to change. Splitting every method into its own class scatters one idea across many files and makes the code harder to follow.
How do you know a class violates SRP?
Ask who would request a change to each method. If the answers are different teams, such as finance for tax and design for layout, the class has several responsibilities. Another sign: tests that need a database just to check arithmetic.
What is the difference between SRP and separation of concerns?
Separation of concerns is the broad idea of keeping different aspects of a program apart. Martin cites it as one root of SRP. SRP is narrower and more practical: it tells you where to draw the line, which is around the people or business function that drive changes.
How is SRP related to cohesion?
Martin calls SRP another way to define cohesion and coupling. A cohesive class groups things that change for the same reason. Keeping the rest apart means a tax change cannot break email delivery.
References
- Robert C. Martin, The Clean Code Blog — The Single Responsibility Principle (2014)
- Wikipedia — Single-responsibility principle
- PHP Manual — Properties (readonly properties)
- PHP Manual — Constructors and Destructors (constructor promotion)
- PHP Manual — Object Interfaces
- PHP Manual — Arrays
- PHP Manual — Floating point numbers
- PHP Manual — intdiv
- Python documentation — dataclasses
- Python typing documentation — Protocols and structural subtyping
