SOLID Principles (Part 1): Single Responsibility (SRP) & Open/Closed (OCP)
1. Topic Introduction
Writing Java code that merely compiles is easy—writing OOP code that stays clean and adaptable when requirements change six months later is hard! Robert C. Martin's SOLID Principles are five foundational OOP design guidelines that prevent bloated 'God classes', rigid if-else chains, and fragile dependencies. In Module 4 exams, expect dedicated 6-mark and 9-mark questions asking for definitions, analogies, and Bad vs Good Java designs.
Bad SRP) vs Modular Kitchen Tools (SRP) + Power Strip (OCP)SRP (Single Responsibility): Imagine a machine that washes clothes, bakes bread, AND cuts hair. If the toaster heater breaks, you have to unplug the washing machine to repair it! Instead, keep one dedicated tool per job (Student stores student data; GradeCalculator computes marks; ReportPrinter formats output).
OCP (Open/Closed): Think of a wall power strip (interface). You don't tear open the house wiring every time you buy a new appliance (modifying existing code); you simply plug a new device (extending via new class) into the existing socket!
3. Essential Exam Definitions
4. Detailed Technical Explanation & Syntax
1. Single Responsibility Principle (SRP) – Full Breakdown
Why Needed: Putting student persistence, GPA calculation, and email notifications inside one Student class creates a 'God Class'. Changing email formatting risks breaking GPA logic and forces recompiling/retesting unrelated features.
Bad Design vs Good Design: Bad Design bundles calculateGrade(), saveToDatabase(), and printReceipt() inside Student. Good Design splits them into cohesive focused classes: StudentData, GradeCalculator, and StudentReportPrinter.
Advantages: High cohesion, minimal regression bugs, easier unit testing, parallel team development, and simpler readability.
2. Open/Closed Principle (OCP) – Full Breakdown
Why Needed: Consider an AreaCalculator using if (shape instanceof Rectangle) ... else if (shape instanceof Circle) .... Every time a new shape (Triangle) is added, you MUST edit AreaCalculator—violating OCP and risking bugs in existing tested logic!
Bad Design vs Good Design: Replace conditional type checks with an abstraction (interface Shape { double area(); }). Rectangle, Circle, and future Triangle each implement Shape. AreaCalculator simply calls s.area(), remaining completely untouched when Triangle is introduced!
Advantages: Zero risk to verified existing code, seamless feature plug-in extensibility, and clean polymorphism.
5. Working Principle: How Abstraction Enforces OCP in Java
- Identify the axis of frequent change (e.g., new Discount rules, new Payment modes, new Shapes).
- Extract an
interfaceorabstract classrepresenting that stable contract (DiscountPolicy). - To add a new rule (
FestivalDiscount), write a NEW class implementingDiscountPolicy—zero edits toInvoiceCalculator!
6. Examination-Ready Diagrams
SOLID Principles Overview
Visual summary of Robert C. Martin's five SOLID object-oriented design principles that eliminate rigid, fragile, and tightly coupled code.
- S – Single Responsibility: A class should have only one reason to change.
- O – Open/Closed: Open for extension, closed for modification.
- L – Liskov Substitution: Subtypes must be substitutable for their base types without breaking behavior.
- I – Interface Segregation: Prefer small, focused interfaces over fat monolithic interfaces.
- D – Dependency Inversion: High-level modules depend on abstractions, not concrete low-level classes.
- SRP splits mixed responsibilities into cohesive single-purpose classes.
- OCP & DIP insert interfaces/abstractions so new features are added via new implementations, not edits.
- LSP ensures inheritance hierarchies respect behavioral contracts.
- ISP ensures clients only implement methods they actually use.
- Draw 5 vertical pillars or stacked blocks labeled S, O, L, I, D with the exact 1-line definition and Java mechanism (
Split classes,Interface/Polymorphism,Safe Subtyping,Small Interfaces,Inject Abstractions).
7. Complete Java Code Examples & Tracing
| 1 | // BAD DESIGN (Violates SRP): Mixes data, grade calculation, AND printing! |
| 2 | class BadStudent { |
| 3 | String name; |
| 4 | int marks; |
| 5 | BadStudent(String name, int marks) { this.name = name; this.marks = marks; } |
| 6 | String computeGrade() { return marks >= 40 ? "PASS" : "FAIL"; } |
| 7 | void printFormattedReport() { System.out.println("[BAD] " + name + ": " + computeGrade()); } |
| 8 | } |
| 9 | |
| 10 | // GOOD DESIGN (Follows SRP): Each class has ONE responsibility / reason to change |
| 11 | class StudentRecord { |
| 12 | private final String name; |
| 13 | private final int marks; |
| 14 | StudentRecord(String name, int marks) { this.name = name; this.marks = marks; } |
| 15 | String getName() { return name; } |
| 16 | int getMarks() { return marks; } |
| 17 | } |
| 18 | |
| 19 | class GradeEvaluator { |
| 20 | String evaluate(StudentRecord student) { |
| 21 | return student.getMarks() >= 24 ? "PASS" : "FAIL"; // KTU 24/60 pass threshold |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | class ReportPrinter { |
| 26 | void print(StudentRecord student, String grade) { |
| 27 | System.out.println("[SRP Good] Student: " + student.getName() + " | Result: " + grade); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | public class SrpDesignDemo { |
| 32 | public static void main(String[] args) { |
| 33 | StudentRecord sr = new StudentRecord("Arjun", 52); |
| 34 | GradeEvaluator evaluator = new GradeEvaluator(); |
| 35 | ReportPrinter printer = new ReportPrinter(); |
| 36 | printer.print(sr, evaluator.evaluate(sr)); |
| 37 | } |
| 38 | } |
[SRP Good] Student: Arjun | Result: PASS
classprivatefinal- Thinking SRP means 'each class can only have ONE method' — WRONG! A class can have several related methods (
deposit,withdraw,getBalance) as long as they serve ONE cohesive responsibility/actor.
BadDiscountService against extensible polymorphism in GoodBillingService.| 1 | // BAD DESIGN (Violates OCP): Must edit this method every time a new discount type arrives! |
| 2 | class BadBilling { |
| 3 | double applyDiscount(String type, double amount) { |
| 4 | if (type.equals("REGULAR")) return amount * 0.95; |
| 5 | else if (type.equals("STUDENT")) return amount * 0.85; |
| 6 | return amount; |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | // GOOD DESIGN (Follows OCP): Closed for modification, open for extension |
| 11 | interface DiscountStrategy { |
| 12 | double apply(double amount); |
| 13 | } |
| 14 | |
| 15 | class RegularDiscount implements DiscountStrategy { |
| 16 | @Override |
| 17 | public double apply(double amount) { return amount * 0.95; } |
| 18 | } |
| 19 | |
| 20 | class StudentDiscount implements DiscountStrategy { |
| 21 | @Override |
| 22 | public double apply(double amount) { return amount * 0.85; } |
| 23 | } |
| 24 | |
| 25 | // Adding FestivalDiscount requires ZERO edits to GoodBilling! |
| 26 | class FestivalDiscount implements DiscountStrategy { |
| 27 | @Override |
| 28 | public double apply(double amount) { return amount * 0.80; } |
| 29 | } |
| 30 | |
| 31 | class GoodBilling { |
| 32 | double calculateFinalPrice(double amount, DiscountStrategy strategy) { |
| 33 | return strategy.apply(amount); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | public class OcpDesignDemo { |
| 38 | public static void main(String[] args) { |
| 39 | GoodBilling billing = new GoodBilling(); |
| 40 | System.out.println("Student price on 1000: " + billing.calculateFinalPrice(1000, new StudentDiscount())); |
| 41 | System.out.println("Festival price on 1000: " + billing.calculateFinalPrice(1000, new FestivalDiscount())); |
| 42 | } |
| 43 | } |
Student price on 1000: 850.0 Festival price on 1000: 800.0
interfaceimplements@Override- Using
instanceofladders inside calculators instead of polymorphic method overriding.
Real-World Applications
- SRP separates MVC layers (Model data vs View rendering vs Controller logic).
- OCP powers payment plugins (
UpiPayment,CardPayment) and SwingLayoutManagerextensions.
Important KTU Exam Points
- For EVERY SOLID principle question, always structure your answer into: (1) Definition, (2) Why needed, (3) Bad Design snippet, (4) Good Design snippet, (5) Advantages.
Memory Techniques & Revision
- S = 'Single Reason to Change'; O = 'Extend via Interface, Don't Edit Existing Core'.
Common Pitfalls to Avoid
- Defining SRP as '1 method per class' instead of '1 responsibility / 1 reason to change'.
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: SRP and OCP are the first two SOLID principles formulated by Robert C. Martin to build modular, maintainable, and extensible OOP software.
- SRP Definition: A class should have only one responsibility and therefore only one reason to change.
- SRP Bad vs Good: Mixing data storage, calculation, and report printing inside one
Studentclass creates coupling; splitting them intoStudentRecord,GradeEvaluator, andReportPrinterisolates changes. - OCP Definition: Classes/modules should be open for extension but closed for modification.
- OCP Bad vs Good: Hardcoded
if-elsediscount checks require modifying existing code for new tiers; extractinginterface DiscountStrategylets new discounts plug in without editingBillingService.
Quick Understanding Check
1. Which principle is violated when adding a new PaymentType forces editing an existing if-else block inside PaymentProcessor?