KTU OOP Java2024 Scheme • 60M ESE
MODULE 4/Section 1: SOLID Principles in Java

SOLID Principles (Part 1): Single Responsibility (SRP) & Open/Closed (OCP)

HIGH PRIORITY (Prep Guide)Official Syllabus + Supplementary~18 min study
Official KTU 2024 Syllabus Topics Covered Here
Single Responsibility Principle (SRP)Open/Closed Principle (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.

2. Start From Zero: Swiss Army Knife (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!

Key Takeaway: SRP: A class should have ONE and ONLY ONE reason to change. OCP: Software entities should be OPEN for extension (adding new subclasses/implementations), yet CLOSED for modification (leaving tested core code untouched).

3. Essential Exam Definitions

Single Responsibility Principle (SRP)
First SOLID principle stating that every class or module should have responsibility over a single part of functionality—meaning it should have only ONE reason to change.
Open/Closed Principle (OCP)
Second SOLID principle stating that software entities (classes, modules, methods) should be open for extension (supporting new behaviors), but closed for modification (without altering existing working source code).

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

  1. Identify the axis of frequent change (e.g., new Discount rules, new Payment modes, new Shapes).
  2. Extract an interface or abstract class representing that stable contract (DiscountPolicy).
  3. To add a new rule (FestivalDiscount), write a NEW class implementing DiscountPolicy—zero edits to InvoiceCalculator!

6. Examination-Ready Diagrams

Diagram 13

SOLID Principles Overview

S – SRPSingle Responsibility1 reason to changeO – OCPOpen / ClosedExtend via interfacesL – LSPLiskov SubstitutionSubtypes safe swapI – ISPInterface SegregationSmall role interfacesD – DIPDependency InversionDepend on abstractions

Visual summary of Robert C. Martin's five SOLID object-oriented design principles that eliminate rigid, fragile, and tightly coupled code.

Key Components
  • 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.
Step-by-Step Flow
  1. SRP splits mixed responsibilities into cohesive single-purpose classes.
  2. OCP & DIP insert interfaces/abstractions so new features are added via new implementations, not edits.
  3. LSP ensures inheritance hierarchies respect behavioral contracts.
  4. ISP ensures clients only implement methods they actually use.
How to Draw in KTU Exam
  • 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

SRP: Bad Design (God Class) vs Good Design (Focused Classes)SrpDesignDemo.java
Demonstrates splitting a multi-responsibility class into single-responsibility classes so formatting/tax changes never break core data.
1// BAD DESIGN (Violates SRP): Mixes data, grade calculation, AND printing!
2class 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
11class 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
19class GradeEvaluator {
20 String evaluate(StudentRecord student) {
21 return student.getMarks() >= 24 ? "PASS" : "FAIL"; // KTU 24/60 pass threshold
22 }
23}
24
25class ReportPrinter {
26 void print(StudentRecord student, String grade) {
27 System.out.println("[SRP Good] Student: " + student.getName() + " | Result: " + grade);
28 }
29}
30
31public 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}
Expected Output
[SRP Good] Student: Arjun | Result: PASS
Keywords:classprivatefinal
Common Exam & Coding Mistakes
  • 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.
OCP: Bad Design (`if-else` Branching) vs Good Design (`interface` Extension)OcpDesignDemo.java
Compares rigid type-checking in BadDiscountService against extensible polymorphism in GoodBillingService.
1// BAD DESIGN (Violates OCP): Must edit this method every time a new discount type arrives!
2class 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
11interface DiscountStrategy {
12 double apply(double amount);
13}
14
15class RegularDiscount implements DiscountStrategy {
16 @Override
17 public double apply(double amount) { return amount * 0.95; }
18}
19
20class 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!
26class FestivalDiscount implements DiscountStrategy {
27 @Override
28 public double apply(double amount) { return amount * 0.80; }
29}
30
31class GoodBilling {
32 double calculateFinalPrice(double amount, DiscountStrategy strategy) {
33 return strategy.apply(amount);
34 }
35}
36
37public 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}
Expected Output
Student price on 1000: 850.0
Festival price on 1000: 800.0
Keywords:interfaceimplements@Override
Common Exam & Coding Mistakes
  • Using instanceof ladders 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 Swing LayoutManager extensions.

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 Student class creates coupling; splitting them into StudentRecord, GradeEvaluator, and ReportPrinter isolates changes.
  • OCP Definition: Classes/modules should be open for extension but closed for modification.
  • OCP Bad vs Good: Hardcoded if-else discount checks require modifying existing code for new tiers; extracting interface DiscountStrategy lets new discounts plug in without editing BillingService.
Exam Diagram Note: Draw Diagram 13 (SOLID Overview) and include short Bad vs Good Java classes.

Quick Understanding Check

1. Which principle is violated when adding a new PaymentType forces editing an existing if-else block inside PaymentProcessor?