Separation of Concerns

Divide program into distinct features

Overview

Separation of Concerns (SoC) is a design principle that advocates dividing a program into distinct sections, each addressing a separate concern. A concern is a set of information that affects the code.

This principle is the foundation of many architectural patterns like MVC, layered architecture, and microservices.

Key Concepts

Divide program into distinct sections

Each section handles one concern

Concerns should have minimal overlap

Enables independent development and testing

Foundation for modular design

Code Example

java
1// ❌ BAD: Mixed concerns
2class UserManager {
3    public void registerUser(String name, String email, String password) {
4        // Validation (concern 1)
5        if (email == null || !email.contains("@")) {
6            throw new IllegalArgumentException("Invalid email");
7        }
8        
9        // Business logic (concern 2)
10        String hashedPassword = hashPassword(password);
11        User user = new User(name, email, hashedPassword);
12        
13        // Database (concern 3)
14        Connection conn = DriverManager.getConnection(DB_URL);
15        PreparedStatement stmt = conn.prepareStatement(
16            "INSERT INTO users VALUES (?, ?, ?)");
17        stmt.executeUpdate();
18        
19        // Email notification (concern 4)
20        Session session = Session.getInstance(mailProps);
21        MimeMessage message = new MimeMessage(session);
22        Transport.send(message);
23        
24        // Logging (concern 5)
25        System.out.println("User registered: " + email);
26    }
27}
28
29// ✅ GOOD: Separated concerns
30// Validation concern
31class UserValidator {
32    public void validate(UserDTO dto) {
33        if (dto.getEmail() == null || !dto.getEmail().contains("@")) {
34            throw new ValidationException("Invalid email");
35        }
36    }
37}
38
39// Business logic concern
40class UserService {
41    private UserRepository repository;
42    private NotificationService notifications;
43    private UserValidator validator;
44    
45    public User registerUser(UserDTO dto) {
46        validator.validate(dto);
47        User user = new User(dto.getName(), dto.getEmail(), 
48                            hashPassword(dto.getPassword()));
49        repository.save(user);
50        notifications.sendWelcomeEmail(user);
51        return user;
52    }
53}
54
55// Data access concern
56class UserRepository {
57    public void save(User user) {
58        // Database operations only
59    }
60}
61
62// Notification concern
63class NotificationService {
64    public void sendWelcomeEmail(User user) {
65        // Email operations only
66    }
67}

Each class handles one concern. Changes to email sending don't affect database code.

Real-World Example

  • MVC Pattern: Model (data), View (UI), Controller (logic)
  • Web Application Layers: Presentation, Business, Data Access
  • Operating System: Kernel, Drivers, Applications

Best Practices

  • 1.

    Identify distinct concerns in your system

  • 2.

    Create separate classes/modules for each concern

  • 3.

    Use interfaces to decouple concerns

  • 4.

    Apply at all levels (class, package, service)

  • 5.

    Common concerns: validation, logging, security, persistence

💡 Interview Tips

  • Show layered architecture example

  • Discuss MVC as application of SoC

  • Explain benefits for team collaboration

  • Connect to Single Responsibility Principle

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In
Separation of Concerns - Design Principles | LLD | Revise Algo