Bird
Raised Fist0
LLDsystem_design~15 mins

Single Responsibility Principle in LLD - Deep Dive

Choose your learning style10 modes available
Overview - Single Responsibility Principle
What is it?
The Single Responsibility Principle means that a part of a system, like a class or module, should have only one reason to change. This means it should do just one job or handle one responsibility. Keeping things focused helps make systems easier to understand and fix. It is one of the key ideas in designing clean and maintainable software.
Why it matters
Without this principle, parts of a system try to do too many things at once. This makes them hard to fix or change because one change can break many things. It slows down development and causes bugs. Using this principle helps teams work faster and keeps software reliable and easier to improve over time.
Where it fits
Before learning this, you should understand basic programming concepts like classes, functions, and modules. After this, you can learn about other design principles like Open/Closed Principle and Dependency Inversion Principle. This principle is part of a bigger set called SOLID principles that guide good software design.
Mental Model
Core Idea
Each part of a system should have one clear job to do and one reason to change.
Think of it like...
Think of a Swiss Army knife versus a single-purpose kitchen knife. The kitchen knife does one job very well, making it simple and reliable. The Swiss Army knife tries to do many jobs but can be harder to use and maintain.
┌─────────────────────────────┐
│        System Module        │
├─────────────┬───────────────┤
│ Responsibility A │ Responsibility B │
│  (One job)       │  (Another job)   │
└─────────────────────────────┘

Each box shows a single responsibility handled separately.
Build-Up - 7 Steps
1
FoundationUnderstanding Responsibilities in Code
🤔
Concept: Learn what a responsibility means in software parts like classes or modules.
A responsibility is a specific job or task a part of the system does. For example, a class that manages user data has the responsibility of handling user information. It should not also handle printing reports or sending emails because those are different jobs.
Result
You can identify clear jobs in your code parts and see when they do too many things.
Understanding what a responsibility is helps you spot when code is trying to do too much, which is the first step to applying the principle.
2
FoundationWhy One Reason to Change Matters
🤔
Concept: Learn why having a single reason to change a code part is important.
If a class does many jobs, it can change for many reasons. This makes it fragile because a change for one job might break another. If it has only one reason to change, you can fix or improve it safely without unexpected side effects.
Result
You see how code with one reason to change is easier to maintain and less error-prone.
Knowing that one reason to change reduces bugs and confusion motivates writing focused code.
3
IntermediateIdentifying Violations of Single Responsibility
🤔Before reading on: do you think a class that handles both data storage and user interface violates the principle? Commit to your answer.
Concept: Learn how to spot when a code part breaks the principle by doing multiple jobs.
Look for classes or modules that mix unrelated tasks, like managing data and displaying it. These parts are harder to test and change. Splitting them into focused parts improves clarity and flexibility.
Result
You can find and fix code that mixes responsibilities, improving design.
Recognizing violations helps prevent complex bugs and makes future changes safer.
4
IntermediateApplying Single Responsibility in Design
🤔Before reading on: do you think splitting a class into two smaller classes always improves design? Commit to your answer.
Concept: Learn how to break down code parts into focused responsibilities during design.
When designing, assign each class or module one clear job. For example, separate data handling from user interaction. This separation allows independent changes and easier testing. But avoid splitting too much, which can cause unnecessary complexity.
Result
You create cleaner, more maintainable designs that follow the principle well.
Knowing how to balance splitting responsibilities avoids overcomplicating the system.
5
IntermediateBenefits of Single Responsibility in Teamwork
🤔
Concept: Understand how this principle helps teams work better together.
When code parts have one job, different team members can work on them without conflicts. It also makes code reviews and debugging easier because each part is focused. This leads to faster development and higher quality software.
Result
You see how design principles improve collaboration and productivity.
Understanding teamwork benefits encourages applying the principle beyond just code quality.
6
AdvancedSingle Responsibility in Large Systems
🤔Before reading on: do you think the principle applies only to small code parts or also to big system components? Commit to your answer.
Concept: Learn how the principle scales to large systems and architecture.
In big systems, each service or module should have one responsibility. This makes the system easier to scale, maintain, and deploy. For example, a payment service should only handle payments, not user profiles or notifications.
Result
You understand how to design scalable and maintainable systems using this principle.
Knowing the principle applies at all levels helps build better software architectures.
7
ExpertTrade-offs and Surprises in Applying the Principle
🤔Before reading on: do you think strictly following the principle always leads to better code? Commit to your answer.
Concept: Explore the limits and unexpected effects of applying the principle too rigidly.
Sometimes, splitting responsibilities too much causes many tiny parts that are hard to manage. Also, some responsibilities naturally overlap and separating them can add complexity. Experts balance the principle with practical needs, using experience to decide when to combine or separate.
Result
You gain a nuanced understanding of when and how to apply the principle effectively.
Understanding trade-offs prevents blindly following rules and leads to smarter design decisions.
Under the Hood
At its core, the principle works by limiting the scope of changes to a single responsibility. When a code part has one job, the internal logic is focused and changes affect only that job. This reduces coupling between different concerns and makes the code easier to test and maintain. Internally, this often means fewer dependencies and simpler interfaces.
Why designed this way?
The principle was created to combat the complexity and fragility of software that tries to do too much in one place. Early software often mixed many concerns, causing bugs and slow development. By enforcing a single responsibility, designers aimed to improve modularity, clarity, and maintainability. Alternatives like monolithic designs were simpler initially but failed at scale.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ Responsibility│─────▶│ Responsibility│─────▶│ Responsibility│
│      One      │      │      Two      │      │      Three    │
└───────────────┘      └───────────────┘      └───────────────┘

Each box is a focused module with one reason to change, connected but independent.
Myth Busters - 4 Common Misconceptions
Quick: Does a class with multiple methods always violate the principle? Commit yes or no.
Common Belief:If a class has many methods, it must have multiple responsibilities.
Tap to reveal reality
Reality:A class can have many methods but still have a single responsibility if all methods serve one job.
Why it matters:Misunderstanding this leads to unnecessary splitting of code, causing complexity and confusion.
Quick: Is it better to split every small task into its own class? Commit yes or no.
Common Belief:More splitting always means better adherence to the principle and better design.
Tap to reveal reality
Reality:Excessive splitting can create too many tiny parts, making the system harder to understand and maintain.
Why it matters:Blindly splitting code wastes time and can reduce clarity, hurting productivity.
Quick: Does the principle only apply to code, not to system architecture? Commit yes or no.
Common Belief:Single Responsibility Principle is only about classes or small code parts.
Tap to reveal reality
Reality:It applies at all levels, including modules, services, and entire systems.
Why it matters:Ignoring this broad application can lead to poor system design and scaling problems.
Quick: Can a class have two closely related responsibilities without violating the principle? Commit yes or no.
Common Belief:Any class with more than one responsibility violates the principle.
Tap to reveal reality
Reality:If responsibilities are tightly related and change for the same reason, they can be combined without violation.
Why it matters:Rigid interpretation can cause unnecessary complexity and reduce practical usability.
Expert Zone
1
Responsibilities should be defined by reasons to change, not by the number of functions or lines of code.
2
Sometimes a responsibility spans multiple classes working together, forming a cohesive unit rather than isolated parts.
3
Balancing SRP with other principles like DRY (Don't Repeat Yourself) and YAGNI (You Aren't Gonna Need It) is key to practical design.
When NOT to use
Avoid strict SRP when it leads to excessive fragmentation of code or when responsibilities are naturally intertwined. In such cases, consider cohesive modules or bounded contexts from Domain-Driven Design as alternatives.
Production Patterns
In microservices architecture, each service often follows SRP by focusing on a single business capability. In layered architectures, SRP guides separation of concerns between layers like UI, business logic, and data access.
Connections
Modular Design
Builds-on
Understanding SRP helps grasp modular design because both focus on breaking systems into manageable, independent parts.
Domain-Driven Design
Complementary
SRP aligns with Domain-Driven Design's idea of bounded contexts, where each context has a clear responsibility within the domain.
Lean Manufacturing
Analogous
Both SRP and lean manufacturing emphasize eliminating waste and focusing on one task at a time to improve quality and efficiency.
Common Pitfalls
#1Trying to put too many unrelated jobs into one class.
Wrong approach:class UserManager { saveUserData() { /* saves user */ } sendEmail() { /* sends email */ } generateReport() { /* creates report */ } }
Correct approach:class UserManager { saveUserData() { /* saves user */ } } class EmailSender { sendEmail() { /* sends email */ } } class ReportGenerator { generateReport() { /* creates report */ } }
Root cause:Misunderstanding that one class should only have one reason to change leads to mixing unrelated responsibilities.
#2Splitting code into too many tiny classes that are hard to manage.
Wrong approach:class UserNameValidator {} class UserEmailValidator {} class UserPasswordValidator {}
Correct approach:class UserValidator { validateName() {} validateEmail() {} validatePassword() {} }
Root cause:Over-applying SRP without considering cohesion and practical usability causes unnecessary fragmentation.
#3Believing SRP only applies to code, ignoring system-level design.
Wrong approach:Building a monolithic system where one module handles payments, user profiles, and notifications.
Correct approach:Designing separate services for payments, user profiles, and notifications, each with a single responsibility.
Root cause:Limited view of SRP scope leads to poor system architecture and scaling issues.
Key Takeaways
The Single Responsibility Principle means each part of a system should have one clear job and one reason to change.
Following this principle makes code easier to understand, test, and maintain by reducing complexity and coupling.
Applying SRP at all levels, from classes to entire systems, leads to better design and scalability.
Blindly splitting code or ignoring related responsibilities can harm design; balance and judgment are essential.
Understanding SRP helps improve teamwork, productivity, and software quality in real-world projects.

Practice

(1/5)
1. What does the Single Responsibility Principle (SRP) mean in simple terms?
easy
A. A class should handle multiple tasks to reduce the number of classes.
B. Each class or module should have only one job or responsibility.
C. All functions should be written in a single class for simplicity.
D. Classes should share responsibilities to improve collaboration.

Solution

  1. Step 1: Understand the principle's core idea

    The Single Responsibility Principle states that a class or module should have one and only one reason to change, meaning it should do one job.
  2. Step 2: Match the explanation to the options

    Each class or module should have only one job or responsibility. clearly states that each class or module should have only one job, which matches the principle.
  3. Final Answer:

    Each class or module should have only one job or responsibility. -> Option B
  4. Quick Check:

    Single Responsibility Principle = One job per class [OK]
Hint: One class, one job keeps code clean and simple [OK]
Common Mistakes:
  • Thinking one class should do many tasks
  • Believing all code should be in one place
  • Confusing SRP with code reuse
2. Which of the following class names best follows the Single Responsibility Principle?
easy
A. UserAuthenticator
B. DataProcessorAndReportGenerator
C. UserManagerAndLogger
D. FileHandlerAndNetworkSender

Solution

  1. Step 1: Analyze class names for single responsibility

    Classes with multiple responsibilities in their names violate SRP. UserManagerAndLogger, DataProcessorAndReportGenerator, and FileHandlerAndNetworkSender suggest multiple jobs.
  2. Step 2: Identify the class with one clear responsibility

    UserAuthenticator clearly focuses on one task: authenticating users, which aligns with SRP.
  3. Final Answer:

    UserAuthenticator -> Option A
  4. Quick Check:

    Class name with one job = UserAuthenticator [OK]
Hint: Class name shows one clear job means SRP followed [OK]
Common Mistakes:
  • Choosing classes with multiple jobs in name
  • Ignoring SRP and mixing responsibilities
  • Assuming longer names are better
3. Given this Python class, what is the main SRP violation?
class OrderProcessor:
    def process_order(self, order):
        self.validate_order(order)
        self.save_order(order)
        self.send_confirmation_email(order)

    def validate_order(self, order):
        pass

    def save_order(self, order):
        pass

    def send_confirmation_email(self, order):
        pass
medium
A. The class handles order validation, saving, and email sending, mixing responsibilities.
B. The class does not validate the order properly.
C. The class should not have any methods.
D. The class only processes orders and follows SRP.

Solution

  1. Step 1: Identify responsibilities in the class

    The class OrderProcessor validates orders, saves orders, and sends confirmation emails. These are three distinct jobs.
  2. Step 2: Check SRP compliance

    SRP requires one responsibility per class. Mixing validation, saving, and emailing violates SRP.
  3. Final Answer:

    The class handles order validation, saving, and email sending, mixing responsibilities. -> Option A
  4. Quick Check:

    Multiple jobs in one class = SRP violation [OK]
Hint: One class, one job; multiple jobs mean SRP broken [OK]
Common Mistakes:
  • Ignoring multiple responsibilities in one class
  • Thinking multiple methods mean multiple classes
  • Assuming SRP allows all related tasks in one class
4. You have a class that both calculates taxes and generates invoices. What is the best way to fix this SRP violation?
medium
A. Combine tax calculation and invoice generation into a single method.
B. Add more methods to handle discounts and payments in the same class.
C. Split the class into two: one for tax calculation and one for invoice generation.
D. Remove tax calculation and keep only invoice generation.

Solution

  1. Step 1: Identify the problem with the current class

    The class does two jobs: calculating taxes and generating invoices, which breaks SRP.
  2. Step 2: Apply SRP by separating responsibilities

    Splitting into two classes, each with one responsibility, fixes the violation and improves maintainability.
  3. Final Answer:

    Split the class into two: one for tax calculation and one for invoice generation. -> Option C
  4. Quick Check:

    Separate classes for separate jobs = SRP fix [OK]
Hint: Split mixed jobs into separate classes to follow SRP [OK]
Common Mistakes:
  • Adding unrelated methods to the same class
  • Combining jobs into one method
  • Removing needed functionality instead of splitting
5. You are designing a system for a library. Which design best follows the Single Responsibility Principle?
hard
A. A single class 'LibrarySystem' that manages books, users, loans, and notifications.
B. A single class 'Library' that handles everything including maintenance and reporting.
C. One class 'LibraryManager' that handles books and users, and another class 'LoanAndNotificationManager' for loans and alerts.
D. Separate classes: 'BookManager' for books, 'UserManager' for users, 'LoanManager' for loans, and 'NotificationService' for alerts.

Solution

  1. Step 1: Analyze each design for responsibility separation

    Designs with a single class handling books, users, loans, and notifications, or a single class handling everything, put many jobs into one class, violating SRP. Designs with one class for books and users, and another for loans and notifications, mix multiple jobs in each class.
  2. Step 2: Identify the design with clear single responsibilities

    Separate classes: 'BookManager' for books, 'UserManager' for users, 'LoanManager' for loans, and 'NotificationService' for alerts. separates concerns into distinct classes, each with one responsibility, following SRP best.
  3. Final Answer:

    Separate classes: 'BookManager' for books, 'UserManager' for users, 'LoanManager' for loans, and 'NotificationService' for alerts. -> Option D
  4. Quick Check:

    Separate classes for separate jobs = SRP followed [OK]
Hint: One class per job in system design follows SRP best [OK]
Common Mistakes:
  • Grouping unrelated responsibilities in one class
  • Mixing multiple jobs in fewer classes
  • Ignoring SRP for convenience
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard