Let’s say you have this big fat class:
class UserService {
public function register($data) {
// 1. Save to DB
// 2. Send welcome email
// 3. Log activity
}
}
Refactoring Steps:
Identify different responsibilities inside the method.
Create separate classes for each responsibility.
Use Dependency Injection to connect them.
Refactored Class:
class UserService {
private $repo;
private $notifier;
private $logger;
public function __construct(UserRepository $repo, UserNotifier $notifier, UserLogger $logger) {
$this->repo = $repo;
$this->notifier = $notifier;
$this->logger = $logger;
}
public function register($data) {
$this->repo->create($data);
$this->notifier->sendWelcomeEmail($data['email']);
$this->logger->log("User registered: " . $data['email']);
}
}
Now, each class has one responsibility, and UserService just coordinates them.
Benefits:
Easier testing (mock only the part you need)
Easier changes (change email logic without touching DB code)
Cleaner, more maintainable code
Top comments (0)