Code that works today still has to change tomorrow: a new payment method, a new report format, a new rule. SOLID is five rules of thumb that keep those changes small and local, so adding a feature doesn't mean editing ten classes and breaking three. Robert C. Martin described the principles around 2000, and Michael Feathers later gave them the acronym. They come up in almost every Java interview.
| Letter | Principle | In one line |
|---|---|---|
| S | Single responsibility | A class should have only one reason to change. |
| O | Open/closed | Add behavior by adding code, not by editing working code. |
| L | Liskov substitution | A subclass must work anywhere its parent is expected. |
| I | Interface segregation | Many small interfaces beat one big one. |
| D | Dependency inversion | Depend on interfaces, not on concrete classes. |
The examples below follow one small online shop.
S: Single Responsibility
A class should have only one reason to change.
"One reason to change" means one person or team that would ask for the change. This class has three:
public class OrderService {
public void placeOrder(Order order) {
// 1. business rules
if (order.items().isEmpty()) {
throw new IllegalArgumentException("Empty order");
}
// 2. database
String sql = "INSERT INTO orders (id, total) VALUES (?, ?)";
// ... JDBC code ...
// 3. email
String body = "<h1>Thanks for your order " + order.id() + "</h1>";
// ... SMTP code ...
}
}The marketing team wants a new email template, the DBA renames a column, the product owner changes a rule: all three edit the same method, and a typo in the email breaks order placement. Testing the rule means setting up a database and a mail server.
Split it by reason to change:
public class OrderRepository {
public void save(Order order) { /* JDBC code only */ }
}
public class OrderEmailer {
public void sendConfirmation(Order order) { /* email code only */ }
}
public class OrderService {
private final OrderRepository repository;
private final OrderEmailer emailer;
public OrderService(OrderRepository repository, OrderEmailer emailer) {
this.repository = repository;
this.emailer = emailer;
}
public void placeOrder(Order order) {
if (order.items().isEmpty()) {
throw new IllegalArgumentException("Empty order");
}
repository.save(order);
emailer.sendConfirmation(order);
}
}OrderService still coordinates the steps, but each detail lives in one place. It's not "one method per class": a class can have many methods, as long as they change for the same reason.
O: Open/Closed
Software should be open for extension, but closed for modification.
Here every new payment method means editing a method that already works:
public class PaymentProcessor {
public void pay(String method, double amount) {
if (method.equals("CARD")) {
// charge the card
} else if (method.equals("PAYPAL")) {
// call PayPal
}
// adding "APPLE_PAY" means editing this method again
}
}Each edit risks breaking card payments while adding Apple Pay, and the same if chain tends to get copied into refunds, receipts and reports.
Put the varying part behind an interface:
public interface PaymentMethod {
void pay(double amount);
}
public class CardPayment implements PaymentMethod {
public void pay(double amount) { /* charge the card */ }
}
public class PayPalPayment implements PaymentMethod {
public void pay(double amount) { /* call PayPal */ }
}
public class PaymentProcessor {
public void pay(PaymentMethod method, double amount) {
method.pay(amount);
}
}Apple Pay is now a new class, ApplePayPayment. PaymentProcessor and the existing payment classes don't change, and their tests keep passing. This is the strategy pattern, the most common way to apply open/closed.
Don't do this up front for everything. A switch over two cases that never change is fine; reach for the interface when the second or third variant shows up.
L: Liskov Substitution
If code works with a parent type, it must keep working with any subtype.
Barbara Liskov stated it in 1987. The classic way to break it is a subclass that can't do what the parent promises:
public class Bird {
public void fly() { System.out.println("Flying"); }
}
public class Penguin extends Bird {
@Override
public void fly() {
throw new UnsupportedOperationException("Penguins can't fly");
}
}
void migrate(List<Bird> birds) {
birds.forEach(Bird::fly); // crashes when the list holds a penguin
}Penguin compiles, but code written for Bird now needs if (bird instanceof Penguin) checks. Those checks are the warning sign.
The fix is a better model: not every bird flies, so flying shouldn't be on Bird.
public class Bird {
public void eat() { /* ... */ }
}
public interface Flyer {
void fly();
}
public class Sparrow extends Bird implements Flyer {
public void fly() { System.out.println("Flying"); }
}
public class Penguin extends Bird {
public void swim() { System.out.println("Swimming"); }
}
void migrate(List<Flyer> flyers) {
flyers.forEach(Flyer::fly); // a penguin can't get in here
}Other ways to break Liskov:
- A subclass that accepts less than the parent (the parent takes any amount, the child throws for amounts over 100).
- A subclass that returns less than promised (the parent never returns
null, the child does). - A subclass that breaks a rule the parent keeps. The textbook case:
Square extends Rectangle, wheresetWidthalso changes the height, so code that sets width 5 and height 4 expects area 20 and gets 16.
In short: inheritance is for "can always be used as", not just "is a kind of" in everyday language.
I: Interface Segregation
Clients shouldn't be forced to depend on methods they don't use.
One big interface for every kind of worker in the warehouse:
public interface Worker {
void pickItems();
void packBox();
void driveTruck();
}
public class Robot implements Worker {
public void pickItems() { /* ... */ }
public void packBox() { /* ... */ }
public void driveTruck() {
throw new UnsupportedOperationException(); // robots don't drive
}
}Every class has to implement methods it can't support, which is a Liskov problem waiting to happen. And a change to driveTruck forces every implementation to recompile and be retested.
Split it into small, focused interfaces. A class implements the ones it needs:
public interface Picker { void pickItems(); }
public interface Packer { void packBox(); }
public interface Driver { void driveTruck(); }
public class Robot implements Picker, Packer {
public void pickItems() { /* ... */ }
public void packBox() { /* ... */ }
}
public class Employee implements Picker, Packer, Driver {
public void pickItems() { /* ... */ }
public void packBox() { /* ... */ }
public void driveTruck() { /* ... */ }
}Code that only needs packing asks for a Packer, and doesn't care whether a robot or a person shows up. The JDK does this too: Comparable, Runnable and AutoCloseable each have a single method.
D: Dependency Inversion
High-level code shouldn't depend on low-level details. Both should depend on abstractions.
The shop's business logic is hard-wired to MySQL:
public class ReportService {
private final MySqlOrderDao dao = new MySqlOrderDao();
public double totalSales() {
return dao.findAll().stream().mapToDouble(Order::total).sum();
}
}ReportService is the important code, but it depends on a database detail. Moving to PostgreSQL means editing it, and a unit test needs a real MySQL server.
Turn the arrow around: the high-level code defines the interface it needs, and the detail implements it.
public interface OrderStore {
List<Order> findAll();
}
public class MySqlOrderStore implements OrderStore {
public List<Order> findAll() { /* JDBC code */ }
}
public class ReportService {
private final OrderStore store;
public ReportService(OrderStore store) { // passed in, not created
this.store = store;
}
public double totalSales() {
return store.findAll().stream().mapToDouble(Order::total).sum();
}
}A test now passes a fake in one line, no database needed:
OrderStore fake = () -> List.of(new Order("A1", 20.0), new Order("A2", 5.0));
ReportService service = new ReportService(fake);
assertEquals(25.0, service.totalSales());(OrderStore has one method, so a lambda can implement it.)
Dependency inversion is the principle; dependency injection is the technique of passing dependencies in from outside, through the constructor here. Spring's container does that wiring for you: see dependency injection in Spring.
How They Work Together
The five principles push in the same direction:
- S gives you small classes with clear jobs.
- I gives those classes small interfaces.
- D makes classes depend on those interfaces instead of each other.
- O follows: new behavior is a new implementation of an interface.
- L makes sure any implementation can be plugged in safely.
The result is code where most changes are "add a class" rather than "edit five".
When Not to Apply Them
SOLID is a set of guidelines, not laws. Overdoing it is a real problem too:
| Overdone | What happens | Better |
|---|---|---|
| An interface for every class | UserService + UserServiceImpl everywhere, noise |
Add the interface when a second implementation or a test fake needs it |
| Splitting classes into tiny pieces | Ten files to read to follow one feature | Split by reason to change, not by line count |
| Strategy pattern for two fixed cases | Extra classes for a switch that never changes |
Keep the switch; refactor when a third case comes |
| Abstracting things that won't change | Indirection with no payoff | YAGNI: "you aren't gonna need it" |
A good test: does this change make the next likely change easier? If not, keep the simple version.
Questions Interviewers Ask
What's the difference between dependency inversion and dependency injection? Inversion is the design rule (depend on abstractions). Injection is one way to follow it (receive dependencies instead of creating them). Spring's container is an injection tool.
Is open/closed about never editing code? No. Bug fixes and refactoring are fine. It means that adding a new variant of something shouldn't require editing the code that handles the existing ones.
Why is Square extends Rectangle a Liskov violation if a square is a rectangle? Because a mutable Rectangle promises that width and height can be set independently, and a square can't keep that promise. An immutable Square with no setters would be fine.
Can you give a SOLID example from the JDK? Collections.sort(list, comparator) is open/closed: new sort orders are new Comparators, and sort never changes. List is used through the interface, so ArrayList and LinkedList can be swapped (dependency inversion and Liskov).
Do SOLID principles apply outside Java? Yes. They were written for object-oriented code but the ideas carry over: in TypeScript, React components with one job (S), props typed by small interfaces (I), and hooks or services passed in rather than imported directly (D).
The Answer in Short
- Single responsibility: one reason to change per class. Split by who asks for changes.
- Open/closed: add new behavior with new classes behind an interface, without editing working code.
- Liskov substitution: a subtype must work everywhere its parent does.
instanceofchecks andUnsupportedOperationExceptionare warning signs. - Interface segregation: small, focused interfaces, so nobody implements methods they don't need.
- Dependency inversion: depend on interfaces and receive dependencies from outside, which makes code easy to test and swap.
- Apply them when a change is coming, not everywhere up front.
