A reason for change is a requirement, action, or area of concern that can independently require a software unit to change. Under the Single Responsibility Principle, distinct reasons belong in separate classes. section 3.4.1
A single application can have separate reasons to change:
- Finance may change sales-tax rules; Infrastructure may change database storage; Marketing may change confirmation-email formatting. section 3.4.1
- Combining business logic, persistence, and formatting in one class tangles those concerns: a database change can force retesting unrelated behavior and raise the risk of breakage. section 3.4.1
Listing 3.3 “Before”: Violating SRP
class Player #A
{
constructor(name) { this.name = name; }
// Responsibility 1: Player’s own state/abilities
dribbleBall() { /* ... */ }
// Responsibility 2: Tactical Logic
determineBestPosition() { /* ... */ }
// Responsibility 3: Data Persistence
saveStatsToDatabase() { /* ... */ }
}The Player class combines player actions, tactical decisions, and database saving—a concrete example of multiple reasons to change. section 3.4.1
Listing 3.4 “After”: Following SRP
// Responsibility 1: Manages only the player’s state and actions
class Player
{
constructor(name) { this.name = name; }
dribbleBall() { /* … */ }
}
// Responsibility 2: Manages only tactical decisions
class TacticsEngine { determinesBestPosition(player) { /* … */ } }
// Responsibility 3: Manages only data saving
class PlayerRepository { saveStats(player) { /* … */ } }The refactoring separates player actions, tactical decisions, and data saving into focused classes. section 3.4.1
