Separation of Concerns
Divide your program into distinct sections, each handling a specific responsibility.
What is Separation of Concerns?
SoC is a design principle for separating a program into distinct sections, where each section addresses a separate concern (a set of related functionality).
Goal: Each module/class should handle one aspect of the system. Changes to one concern shouldn't affect others.
Real-World Analogy
Restaurant Kitchen
Chef
Cooks food
Waiter
Serves customers
Cashier
Handles payments
Each role focuses on one concern. Chef doesn't handle payments, waiter doesn't cook.
Code Example
Before: Mixed Concerns
// One class doing everything - BAD!
class UserController {
public void registerUser(Request req) {
// Validation (Concern 1)
if (req.email == null) throw new Error();
if (req.password.length < 8) throw new Error();
// Business Logic (Concern 2)
String hashedPassword = hashPassword(req.password);
// Database (Concern 3)
String sql = "INSERT INTO users...";
database.execute(sql);
// Notification (Concern 4)
sendEmail(req.email, "Welcome!");
// Logging (Concern 5)
log("User registered: " + req.email);
}
}After: Separated Concerns
// Each class handles one concern - GOOD!
// Concern 1: Validation
class UserValidator {
public void validate(UserRequest req) {
if (req.getEmail() == null)
throw new ValidationException("Email required");
if (req.getPassword().length() < 8)
throw new ValidationException("Password too short");
}
}
// Concern 2: Business Logic
class UserService {
private UserValidator validator;
private UserRepository repository;
private NotificationService notifier;
public User register(UserRequest req) {
validator.validate(req);
User user = new User(req.getEmail(),
hashPassword(req.getPassword()));
repository.save(user);
notifier.sendWelcome(user);
return user;
}
}
// Concern 3: Data Access
class UserRepository {
public void save(User user) {
// Database operations only
}
}
// Concern 4: Notifications
class NotificationService {
public void sendWelcome(User user) {
// Email logic only
}
}Benefits
Easier Testing
Test each concern independently with mocks
Better Maintainability
Change one concern without affecting others
Improved Reusability
Reuse components across different parts of the app
Clear Ownership
Different teams can work on different concerns
Common Layered Architecture
Presentation Layer
UI, Controllers, Views
↓
Business Logic Layer
Services, Use Cases, Domain
↓
Data Access Layer
Repositories, DAOs, ORM
↓
Database
SQL, NoSQL, Cache
Interview Tips
- 1.SoC is the foundation of MVC, MVVM, Clean Architecture
- 2.Related to SRP but at a higher level (modules/layers vs classes)
- 3.When designing, ask: "What are the different concerns here?"
- 4.Each concern = potential separate class, module, or service