Skip to content
Chethan Yadav_
Object-Oriented Programming

OOP/Lesson 4 of 5/6 min read

SOLID Principles

The five SOLID design principles with violations and fixes, plus DRY, KISS, YAGNI and the Law of Demeter.


On this page

SOLID

Five principles, popularized by Robert C. Martin, for designing classes that are easy to change, test and extend.

LetterPrincipleOne-liner
SSingle ResponsibilityOne reason to change
OOpen-ClosedExtend without modifying
LLiskov SubstitutionSubtypes must be usable as their base type
IInterface SegregationMany small interfaces beat one fat one
DDependency InversionDepend on abstractions, not concretions

Single Responsibility Principle

A class should have only one reason to change. "Reason to change" means one actor or stakeholder whose requirements drive it.

Violation:

class Invoice {
    double total() { ... }          // business rules
    void saveToDb() { ... }         // persistence
    String toPdf() { ... }          // presentation
}

A change to the PDF layout, the database schema or tax rules all touch the same class. Fix: split into Invoice, InvoiceRepository, and InvoicePdfRenderer.

Signs of an SRP violation: class names with "And" or "Manager", huge files, tests that need many unrelated mocks.

Open-Closed Principle

Software entities should be open for extension but closed for modification. Add new behavior by adding code, not by editing tested code.

Violation:

double area(Shape s) {
    if (s.type == CIRCLE) return Math.PI * s.r * s.r;
    if (s.type == SQUARE) return s.side * s.side;
    // every new shape edits this function
}

Fix with polymorphism:

interface Shape { double area(); }
class Circle implements Shape { public double area() { return Math.PI * r * r; } }
class Square implements Shape { public double area() { return side * side; } }
// new shapes = new classes; area callers never change

Tools for OCP: polymorphism, Strategy pattern, plugins, decorators.

Liskov Substitution Principle

Objects of a subclass must be substitutable for objects of the superclass without breaking correctness. If code works with a Base, it must work with any Derived.

Classic violation: Square extends Rectangle.

void resize(Rectangle r) {
    r.setWidth(5);
    r.setHeight(4);
    assert r.area() == 20;   // fails for Square: setting height also sets width
}

A square is mathematically a rectangle, but not behaviorally substitutable. Fix: make both implement a Shape interface, or make them immutable.

Rules a subclass must follow:

  • Do not strengthen preconditions (accept at least what the parent accepts).
  • Do not weaken postconditions (guarantee at least what the parent guarantees).
  • Preserve the parent's invariants.
  • Do not throw new unexpected exceptions. A ReadOnlyList that throws on add() violates LSP for a List.

Interface Segregation Principle

Clients should not be forced to depend on methods they do not use.

Violation:

interface Worker { void work(); void eat(); void sleep(); }
class Robot implements Worker {
    public void eat() { throw new UnsupportedOperationException(); }  // forced
}

Fix: split into Workable, Eatable, Sleepable. A Robot implements only Workable.

Benefit: smaller interfaces mean fewer reasons for implementers to recompile or change, and clearer contracts.

Dependency Inversion Principle

  1. High-level modules should not depend on low-level modules; both should depend on abstractions.
  2. Abstractions should not depend on details; details should depend on abstractions.

Violation:

class ReportService {
    private MySqlDatabase db = new MySqlDatabase();   // high level knows the low-level detail
}

Fix:

interface Database { List<Row> query(String sql); }
class MySqlDatabase implements Database { ... }
class ReportService {
    private final Database db;
    ReportService(Database db) { this.db = db; }       // injected
}

DIP is the principle; dependency injection is a technique for achieving it; an IoC container automates the injection. See advanced OOP.

Other design principles

DRY

Don't Repeat Yourself: every piece of knowledge should have a single, authoritative representation. Duplicate logic drifts apart and causes bugs when only one copy gets fixed.

Pitfall: over-applying DRY to code that only looks similar but changes for different reasons. That creates coupling. "Duplication is far cheaper than the wrong abstraction."

KISS

Keep It Simple, Stupid: prefer the simplest design that works. Clever code costs more to read, debug and change.

YAGNI

You Aren't Gonna Need It: do not build features or abstractions until they are actually needed. Speculative generality adds code that must be maintained and is often wrong.

Law of Demeter

Talk only to your immediate friends. A method should call methods only on: itself, its parameters, objects it creates, and its direct fields.

// Violation: train wreck, knows the whole structure
order.getCustomer().getAddress().getCity();
 
// Better: ask, do not dig
order.shippingCity();

Reduces coupling to the internal structure of other objects.

Tell, don't ask

Instead of asking an object for data and making decisions for it, tell it what to do. account.withdraw(50) instead of checking account.getBalance() and calling setBalance().

Applying SOLID in interviews

SmellPrinciple to citeFix
God class doing everythingSRPSplit by responsibility
Long if/else or switch on typeOCPPolymorphism or Strategy
Subclass throws "not supported"LSP, ISPRework hierarchy, split interface
Class implements empty methodsISPSmaller interfaces
new ConcreteClass() inside business logicDIPInject an interface
a.getB().getC().doX()Law of DemeterAdd a method on a
SOLID is a set of heuristics, not laws. Applying every principle everywhere leads to over-engineering with dozens of one-method interfaces. Use them where change is likely.

Quick revision

  • SRP: one reason to change; split by actor.
  • OCP: add new classes instead of editing switch statements.
  • LSP: subclasses must honor the parent's contract; Square extends Rectangle is the classic violation.
  • ISP: small, focused interfaces; no forced empty methods.
  • DIP: depend on abstractions; inject concrete implementations.
  • DRY, KISS, YAGNI keep code lean; Law of Demeter avoids train-wreck call chains.