QUICK REFERENCE

SOLID Principles Cheat Sheet

The 5 architectural pillars for writing maintainable and scalable object-oriented code.

S.O.L.I.D

Single Responsibility (SRP)

A class should have one, and only one, reason to change.

// BAD: Mixed responsibilities
class User {
void save() { db.save(this); }
void sendEmail() { email.send(this); }
}
// GOOD: Separated concerns
class UserRepository {
void save(User u) { ... }
}
class EmailService {
void sendWelcome(User u) { ... }
S.O.L.I.D

Open/Closed (OCP)

Entities should be open for extension, but closed for modification.

// BAD: modifying for new shapes
class AreaCalc {
double calculate(Object shape) {
if (shape instanceof Circle) ...
else if (shape instanceof Square) ...
}
}
// GOOD: Polymorphism
interface Shape { double area(); }
class Circle implements Shape { ... }
class Square implements Shape { ... }
S.O.L.I.D

Liskov Substitution (LSP)

Subtypes must be substitutable for their base types without breaking the program.

// BAD: Square breaks Rectangle logic
class Square extends Rectangle {
void setWidth(int w) {
this.width = w; this.height = w;
}
}
// GOOD: Separate interfaces or Composition
interface Shape { int area(); }
class Rectangle implements Shape { ... }
class Square implements Shape { ... }
S.O.L.I.D

Interface Segregation (ISP)

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

// BAD: Bloated interface
interface Worker {
void work();
void eat();
}
// GOOD: Segregated interfaces
interface Workable { void work(); }
interface Eatable { void eat(); }
class Robot implements Workable {
public void work() { ... }
// No need to implement eat()
}
S.O.L.I.D

Dependency Inversion (DIP)

High-level modules should not depend on low-level modules. Both should depend on abstractions.

// BAD: High coupling
class Service {
private MySQLDB db = new MySQLDB();
}
// GOOD: Dependency Injection
interface Database { void save(); }
class Service {
private Database db;
public Service(Database db) {
this.db = db;
}
}