Single Responsibility Principle (SRP)
Definition:
A class should have only one reason to change. That means one responsibility — one job.
Why?
If a class is doing multiple jobs, then changes in one area can break unrelated functionality. This creates a maintenance nightmare.
Example of Violating SRP
class User {
public function createUser($data) {
// Logic to save user to database
}
public function sendWelcomeEmail($email) {
// Logic to send email
}
public function logUserActivity($message) {
// Logic to write to logs
}
}
This User class:
Manages database operations
Sends emails
Handles logging
💣 Problem: If the email system changes, you have to touch this class (risking breaking DB logic).
SRP-Compliant Refactor
class UserRepository {
public function create($data) {
// Save to DB
}
}
class UserNotifier {
public function sendWelcomeEmail($email) {
// Send email
}
}
class UserLogger {
public function log($message) {
// Write to logs
}
}
Now:
If the database changes → Only change UserRepository.
If email service changes → Only change UserNotifier.
Analogy:
Think of a restaurant kitchen:
Chef cooks food
Waiter serves food
Cashier handles billing
If the waiter suddenly starts cooking and collecting payments, one problem in any area could break the whole process.
Rule of Thumb:
Whenever you find yourself writing a class that uses "and" in its description (“This class handles user registration and email sending”), you’re probably breaking SRP.
Top comments (0)