AdvancedOOP Concepts · Lesson 9 of 10 · Updated ·
SOLID Principles in Java — Refactoring a Real Class Step by Step
The earlier SOLID lesson explained the five rules with short Python snippets. Interviews for Java roles usually ask you to show SOLID in Java: "Here is a class. What is wrong with it, and how would you fix it?" In this lesson we take one messy class from a college results system and fix it, one principle at a time. Every program is complete and runnable (class Main).
1. The messy starting point
A college wants to publish semester results. A first-year student writes this:
import java.util.*;
class ResultService {
// 1. calculates 2. formats 3. "saves" 4. notifies — four jobs in one class
String publish(String name, int[] marks, String channel) {
int total = 0;
for (int m : marks) total += m;
double pct = total * 100.0 / (marks.length * 100);
String grade = pct >= 75 ? "Distinction" : pct >= 60 ? "First class" : "Pass";
String line = name + ": " + pct + "% (" + grade + ")";
System.out.println("Saved to MySQL -> " + line);
if (channel.equals("SMS")) System.out.println("SMS: " + line);
else if (channel.equals("EMAIL")) System.out.println("EMAIL: " + line);
return line;
}
}
public class Main {
public static void main(String[] args) {
new ResultService().publish("Asha", new int[]{82, 74, 91}, "SMS");
}
}
Saved to MySQL -> Asha: 82.33333333333333% (Distinction)
SMS: Asha: 82.33333333333333% (Distinction)
It works, but look at how many reasons to change this class has: the grading rules change, the output format changes, the database moves from MySQL to PostgreSQL, the college adds WhatsApp. Every one of those edits touches the same method, and you cannot test the grade calculation without also "saving" and "sending".
2. S — Single Responsibility: one reason to change
Split the class so that each part has one job. The grade logic now lives alone and can be tested alone:
class GradeCalculator {
double percentage(int[] marks) {
int total = 0;
for (int m : marks) total += m;
return Math.round(total * 10.0 / marks.length) / 10.0; // average of marks out of 100, one decimal
}
String grade(double pct) {
if (pct >= 75) return "Distinction";
if (pct >= 60) return "First class";
return "Pass";
}
}
class ResultFormatter {
String format(String name, double pct, String grade) {
return name + ": " + pct + "% (" + grade + ")";
}
}
public class Main {
public static void main(String[] args) {
GradeCalculator calc = new GradeCalculator();
double pct = calc.percentage(new int[]{82, 74, 91});
System.out.println(new ResultFormatter().format("Asha", pct, calc.grade(pct)));
System.out.println(calc.grade(59.9) + ", " + calc.grade(60) + ", " + calc.grade(75));
}
}
Asha: 82.3% (Distinction)
Pass, First class, Distinction
Notice the second line: we tested three boundary values of the grading rule without any database or SMS. That is the practical benefit of SRP — small classes are easy to test.
3. O — Open/Closed: add, don't edit
The if (channel.equals("SMS")) … else if … chain is the classic smell. Adding WhatsApp means editing working code. Instead, make each channel a class behind an interface. New channel = new class; the code that sends never changes.
import java.util.*;
interface Notifier {
void send(String message);
}
class SmsNotifier implements Notifier {
public void send(String message) { System.out.println("SMS: " + message); }
}
class EmailNotifier implements Notifier {
public void send(String message) { System.out.println("EMAIL: " + message); }
}
class WhatsAppNotifier implements Notifier { // added later — nothing else edited
public void send(String message) { System.out.println("WHATSAPP: " + message); }
}
public class Main {
static void notifyAll(List<Notifier> channels, String message) {
for (Notifier n : channels) n.send(message); // never changes
}
public static void main(String[] args) {
notifyAll(List.of(new SmsNotifier(), new EmailNotifier(), new WhatsAppNotifier()),
"Asha: 82.3% (Distinction)");
}
}
SMS: Asha: 82.3% (Distinction)
EMAIL: Asha: 82.3% (Distinction)
WHATSAPP: Asha: 82.3% (Distinction)
"Closed for modification" does not mean you can never edit a file. It means the stable core (here, notifyAll) does not need editing when a new variety of something arrives.
4. L — Liskov Substitution: subclasses must keep promises
Suppose someone adds a DemoNotifier for the trial version that throws an exception because demo users cannot send messages:
interface Notifier { void send(String message); }
class SmsNotifier implements Notifier {
public void send(String message) { System.out.println("SMS: " + message); }
}
class DemoNotifier implements Notifier { // breaks the promise "send() delivers the message"
public void send(String message) { throw new UnsupportedOperationException("demo mode"); }
}
public class Main {
public static void main(String[] args) {
Notifier[] all = { new SmsNotifier(), new DemoNotifier() };
for (Notifier n : all) {
try {
n.send("Result out");
} catch (UnsupportedOperationException e) {
System.out.println("Crashed: " + e.getMessage());
}
}
}
}
SMS: Result out
Crashed: demo mode
Code that was written for "any Notifier" now crashes when given this one. That violates Liskov: an implementation must be usable wherever the parent type is expected, with no surprises. The fix is not to throw — a demo notifier can log the message and do nothing harmful, or demo mode should not be a Notifier at all. Warning signs: UnsupportedOperationException in an override, or callers writing if (n instanceof DemoNotifier).
5. I — Interface Segregation: small interfaces
Imagine one big interface ResultChannel with send(), sendAttachment() and readReceipts(). SMS cannot send attachments, so SmsNotifier would be forced to implement a method it cannot support — which leads straight back to Liskov problems. Split it:
| Big interface (bad) | Small interfaces (good) |
|---|---|
ResultChannel { send(); sendAttachment(); readReceipts(); } | Notifier { send(); } |
SMS must fake sendAttachment() | AttachmentSender { sendAttachment(); } |
ReceiptReader { readReceipts(); } |
EmailNotifier implements Notifier, AttachmentSender; SmsNotifier implements Notifier only. In Java a class can implement many interfaces, so small ones cost nothing.
6. D — Dependency Inversion: depend on interfaces
The last problem: ResultService created its own MySQL storage inside itself. High-level policy (publishing results) should not depend on low-level details (which database). Both should depend on an interface, and the concrete object is passed in through the constructor.
import java.util.*;
interface ResultStore { void save(String line); int count(); }
class InMemoryStore implements ResultStore { // used in tests — no database needed
private final List<String> rows = new ArrayList<>();
public void save(String line) { rows.add(line); }
public int count() { return rows.size(); }
}
interface Notifier { void send(String message); }
class SmsNotifier implements Notifier {
public void send(String message) { System.out.println("SMS: " + message); }
}
class ResultService {
private final ResultStore store;
private final Notifier notifier;
ResultService(ResultStore store, Notifier notifier) { // dependencies injected
this.store = store;
this.notifier = notifier;
}
void publish(String line) {
store.save(line);
notifier.send(line);
}
}
public class Main {
public static void main(String[] args) {
ResultStore store = new InMemoryStore();
ResultService service = new ResultService(store, new SmsNotifier());
service.publish("Asha: 82.3% (Distinction)");
service.publish("Ravi: 64.0% (First class)");
System.out.println("Rows saved: " + store.count());
}
}
SMS: Asha: 82.3% (Distinction)
SMS: Ravi: 64.0% (First class)
Rows saved: 2
To use MySQL in production, write MySqlStore implements ResultStore and pass that instead — ResultService does not change. This is exactly what Spring does for you: it creates the objects and passes them into constructors (dependency injection).
7. How to answer "explain SOLID" in an interview
- Name the principle in one line.
- Show the smell it fixes (a long
if-elseon type, a method that throws "not supported", anew MySqlDatabase()inside a service). - Show the fix in two or three lines of code.
- Say the benefit: easier testing, safer changes.
A good one-line summary: SOLID keeps each class small, lets you add features by adding classes, and lets you swap parts (like the database) without touching business logic.
Common mistakes
- Splitting classes so much that a simple feature is spread over ten files. SOLID is a guide for code that keeps changing, not a rule to apply blindly to a 30-line program.
- Thinking Open/Closed means "never edit a file". It means the stable core should not need edits when new variants are added.
- Confusing Dependency Inversion (the principle: depend on abstractions) with Dependency Injection (one technique: pass dependencies in).
- Implementing an interface method by throwing
UnsupportedOperationException— usually a sign the interface is too big (ISP) or the class should not implement it (LSP).
Quick recap
- S: one reason to change —
GradeCalculator,ResultFormatter,ResultStore,Notifiereach do one job. - O: new behaviour = new class implementing an interface, not a new
else if. - L: every implementation must honour the parent's contract; no surprise exceptions.
- I: several small interfaces beat one large one.
- D: high-level code depends on interfaces; concrete classes are passed in through constructors.