Single Responsibility Principle (Java)

Context: SOLID · the S · “separation of concerns” made concrete · raises cohesion Problem it solves: spot a class doing several unrelated jobs and split it so each class changes for exactly one reason.

Quick Revision

  • 🎯 Trigger: a class has methods/fields that change for different reasons âž” split it, one responsibility per class.
  • ⚡ Key Constraint: the test is “reason to change”, not line count — gather things that change for the same reason, separate those that change for different reasons (Martin).

đź”§ Minimal Working Example

// SMELL: a God class — Tutor knows about lab, contact, and unit concerns
class Tutor {
    private String name, email; private int labNumber, numOfStudents; private String unitCode;
    void setLab(int labNumber, int n) { /* lab concern */ }
    void setUnitCode(String c) { /* unit concern + validation */ }
    // ...many unrelated reasons to change
}
 
// FIX: separate by reason-to-change
class Lab   { private Tutor[] tutors; private int labNumber, numOfStudents; }
class Tutor { private String givenName, familyName, staffId, email; }

Expected output: each class now has one reason to change; a lab-scheduling change touches Lab, a name-format change touches Tutor.

  • God class âž” one class holds all methods while others just carry data — procedural, not OO; many reasons to change.
  • Split trigger âž” two+ distinct behaviours, or changing one field cascades to unrelated features.
  • Scope âž” SRP applies to classes and methods and fields (name things precisely).

🏛️ Structure (God class ➔ split)

classDiagram
    class Lab {
        -int labNumber
        -int numOfStudents
    }
    class Tutor {
        -String givenName
        -String familyName
        -String staffId
        -String email
    }
    Lab o-- Tutor

(The Tutor God class splits by reason to change: lab-scheduling concerns → Lab, personal-detail concerns → Tutor. Each class now has one reason to change ⇒ ↑ cohesion.)

🔀 Variations — reason-to-change

  • Employee example âž” computePay() (finance’s concern) and reportHours() (operations’ concern) change for different stakeholders âž” belong in different classes.
  • Over-applying SRP âž” splitting until classes are trivially tiny overcomplicates the design; Martin targeted the common tendency to make classes too large, not to atomise everything.

✍️ Practice

⚠️ Common Mistakes

  • đź’ˇ “One responsibility” ≠ “one method” âž” a class may have many methods as long as they serve one reason to change.
  • đź’ˇ Measure with LCOM âž” a class whose methods split into field-clusters that don’t overlap has low cohesion âž” SRP candidate.
  • đź’ˇ Cohesion payoff (Domain B) âž” good SRP means when a responsibility changes, everything you need is in one place and nothing extra gets in the way.