Bird
Raised Fist0
Interview Prepoop-design-patternseasyAmazonGoogleMicrosoftFlipkartRazorpayCREDSwiggy

Single Responsibility Principle - One Class, One Reason to Change

Choose your preparation mode3 modes available
🎯
Single Responsibility Principle - One Class, One Reason to Change
easyOOPAmazonGoogleMicrosoft

Imagine a library where each book covers only one topic thoroughly, so if you want to update information about that topic, you only need to revise that one book, not the entire library.

💡 Beginners often confuse 'responsibility' with 'functionality' or 'methods count', leading them to group unrelated tasks in one class simply because they seem related at a surface level.
📋
Interview Question

Explain the Single Responsibility Principle (SRP) in object-oriented design. What does it mean for a class to have a single responsibility, and why is it important? How does SRP improve code maintainability and flexibility?

Definition of responsibility in SRP contextReason to change as the guiding factor for class designImpact of SRP on cohesion and coupling
💡
Scenario & Trace
ScenarioA class handles both user authentication and logging user activities.
Initially, the class authenticates users and logs their login times. Later, a requirement changes the logging format. Because authentication and logging are in the same class, changing logging affects authentication code, increasing risk and complexity.
ScenarioSeparating payment processing and invoice generation into two classes.
PaymentProcessor class handles payment transactions, while InvoiceGenerator class creates invoices. Changes in invoice format do not affect payment logic, and vice versa, making the system easier to maintain and extend.
  • What if a class seems to have multiple responsibilities but they share the same reason to change?
  • How to handle utility/helper classes that provide multiple unrelated functions?
  • What happens if splitting responsibilities leads to excessive fragmentation and many tiny classes?
⚠️
Common Mistakes
Confusing 'responsibility' with 'number of methods or functions'

Interviewer thinks candidate lacks understanding of SRP's core idea.

✅ Explain that responsibility means a reason to change, not just method count.

Believing SRP means one method per class

Interviewer doubts candidate's grasp of practical design.

✅ Clarify that a class can have many methods as long as they serve one responsibility.

Ignoring that multiple responsibilities can share the same reason to change

Interviewer sees candidate as rigid and unable to reason about design trade-offs.

✅ Emphasize that SRP is about reasons to change, so related responsibilities with one reason can coexist.

Thinking SRP applies only to classes, not modules or functions

Interviewer questions candidate's broader understanding of SRP.

✅ Mention SRP is a design principle applicable at multiple levels, including modules and functions.

🧠
Basic Definition - What It Is
💡 This level ensures you can clearly state the principle and its core idea without confusion.

Intuition

A class should have only one reason to change, meaning it should focus on a single responsibility.

Explanation

The Single Responsibility Principle states that every class should have one, and only one, reason to change. This means a class should encapsulate a single part of the functionality provided by the software, ensuring high cohesion within the class. When a class has multiple responsibilities, changes in one area can affect unrelated parts, increasing the risk of bugs and making maintenance harder.

Memory Hook

💡 Think of a class like a specialist doctor: they focus on one specialty rather than trying to treat every illness.

Interview Questions

❓ What does 'one reason to change' mean in SRP?
  • A reason to change corresponds to a responsibility or a stakeholder's concern.
  • If a class has multiple reasons to change, it violates SRP.
⏱
Depth Level
Interview Time30 seconds
Depthbasic

Covers the fundamental definition and why it matters at a high level.

Interview Target: Minimum floor - never go below this

Knowing only this lets you pass initial screening but lacks depth for on-site interviews.

🧠
Mechanism Depth - How It Works
💡 This level is expected in product companies and shows you understand the internal rationale and practical application.

Intuition

SRP reduces coupling and increases cohesion by ensuring each class addresses a single concern, making the system easier to maintain and extend.

Explanation

The Single Responsibility Principle works by identifying distinct responsibilities or reasons to change within a system and assigning each to a separate class. This separation ensures that changes in one responsibility do not ripple through unrelated code, reducing the chance of bugs and simplifying testing. It also improves cohesion, as each class focuses on a well-defined task. For example, separating data persistence from business logic means changes in database schema affect only the persistence class, not the business logic. SRP also facilitates parallel development and clearer code ownership.

Memory Hook

💡 Imagine a factory assembly line where each worker has a single task; if one task changes, only that worker needs retraining, not the entire line.

Interview Questions

❓ How does SRP affect coupling and cohesion?
  • SRP increases cohesion by grouping related functionality in one class.
  • SRP reduces coupling by minimizing dependencies between classes.
  • This leads to easier maintenance and fewer side effects when changing code.
❓ What if two responsibilities share the same reason to change?
  • They can be in the same class since the reason to change is singular.
  • SRP focuses on reasons to change, not just counting methods.
⏱
Depth Level
Interview Time2-3 minutes
Depthintermediate

Demonstrates understanding of how SRP improves design quality and maintainability.

Interview Target: Target level for FAANG on-sites

Mastering this level distinguishes you from most candidates.

📊
Explanation Depth Levels
💡 Choose depth based on interview stage and role; deeper levels impress on-site interviewers.
LevelInterview TimeSuitable ForRisk
Basic Definition30sScreening callToo shallow for on-site interviews
Mechanism Depth2-3 minutesOn-site interviews at FAANG and product companiesRequires good understanding; skipping may lose points
💼
Interview Strategy
💡 Use this guide to structure your explanation clearly and confidently before interviews.

How to Present

Start with a clear definition of SRP.Give a simple real-world analogy or example.Explain how SRP reduces coupling and increases cohesion.Discuss common edge cases and trade-offs.

Time Allocation

Definition: 30s → Example: 1min → Mechanism: 2min → Edge cases: 30s. Total ~4min

What the Interviewer Tests

Interviewer checks if you understand the principle's rationale, can identify responsibilities, and appreciate its impact on maintainability.

Common Follow-ups

  • What if a class has multiple methods but only one reason to change? → It's still SRP compliant.
  • Can SRP lead to too many small classes? → Yes, balance is needed to avoid over-fragmentation.
💡 These follow-ups test your ability to apply SRP pragmatically, not just theoretically.
🔍
Pattern Recognition

When to Use

Asked during OOP design, SOLID principles, or code maintainability discussions.

Signature Phrases

'Explain the Single Responsibility Principle''What does it mean for a class to have one reason to change?''Compare classes with multiple responsibilities vs single responsibility'

NOT This Pattern When

Similar Problems

Practice

(1/5)
1. In designing a parking lot system using OOP, which component is best suited to decide which type of parking spot (e.g., compact, large, handicapped) should be allocated to an incoming vehicle?
easy
A. The ParkingLot class, as it manages all spots and vehicles
B. The ParkingSpot class, since it represents the spot's characteristics
C. The Vehicle class, because it knows its own size and type
D. A Factory or Strategy pattern component that encapsulates the allocation logic

Solution

  1. Step 1: Understand responsibilities

    The Vehicle class only knows about itself, not allocation rules. The ParkingSpot class represents a spot but doesn't decide allocation. The ParkingLot manages overall state but delegating allocation logic to a dedicated component improves modularity.
  2. Step 2: Recognize design pattern role

    The Factory or Strategy pattern encapsulates allocation logic, allowing easy extension and modification without changing core classes.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Allocation logic centralized -> easier to maintain and extend [OK]
Hint: Allocation logic belongs in a dedicated pattern component, not core entities [OK]
Common Mistakes:
  • Assigning allocation responsibility to Vehicle or ParkingSpot classes
  • Putting all logic inside ParkingLot class leading to tight coupling
2. You are designing a payment processing system that must support new payment methods without changing existing code. Which design approach best aligns with the Open/Closed Principle?
easy
A. Creating a new subclass for each payment method that implements a common payment interface
B. Modifying the existing payment processor class to handle new payment methods directly
C. Adding new conditional branches inside the existing payment processor class for each new payment method
D. Using global variables to switch between payment methods at runtime

Solution

  1. Step 1: Identify extension vs modification

    Adding new payment methods should extend behavior without modifying existing classes.
  2. Step 2: Evaluate subclassing with common interface

    Creating subclasses for each payment method allows extension by adding new classes, adhering to OCP.
  3. Step 3: Why other options fail

    Adding new conditional branches inside the existing payment processor class for each new payment method and modifying existing code violate the 'closed for modification' part. Using global variables to switch between payment methods at runtime uses global state, which is unrelated and error-prone.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Extension via polymorphism, no modification of existing code.
Hint: Extend with new classes, don't modify existing ones [OK]
Common Mistakes:
  • Thinking adding conditionals is extension
  • Believing modifying existing code is acceptable if tested
  • Confusing global state management with OCP
3. Which of the following statements about the Diamond Problem and its resolution is INCORRECT?
medium
A. The Diamond Problem occurs when a class inherits from two classes that both inherit from the same base class.
B. The Diamond Problem can be resolved by using virtual inheritance in languages like C++.
C. Method Resolution Order (MRO) is irrelevant to resolving the Diamond Problem.
D. Without proper resolution, the Diamond Problem can cause duplicate base class instances.

Solution

  1. Step 1: Understand the Diamond Problem

    It arises when a class inherits from two classes that share a common ancestor, causing ambiguity and duplication.
  2. Step 2: Virtual inheritance role

    Virtual inheritance in C++ ensures only one instance of the base class exists, resolving duplication.
  3. Step 3: Role of MRO

    MRO is critical in languages like Python to determine method lookup order and resolve ambiguity.
  4. Step 4: Identify incorrect statement

    Method Resolution Order (MRO) is irrelevant to resolving the Diamond Problem. incorrectly claims MRO is irrelevant, which is false.
  5. Final Answer:

    Option C -> Option C
  6. Quick Check:

    MRO is essential for resolving method lookup in diamond inheritance scenarios.
Hint: MRO is key to diamond resolution in dynamic languages
Common Mistakes:
  • Ignoring MRO's role in method lookup
  • Confusing virtual inheritance with method resolution
  • Assuming diamond problem only causes ambiguity, not duplication
4. If you want to allow decorators to be added and removed dynamically at runtime (e.g., undo last added decorator), which modification to the Decorator Pattern implementation is most appropriate?
hard
A. Modify the base class to include flags for each decorator feature
B. Use inheritance to create new subclasses for every add/remove combination
C. Store decorators in a stack data structure and update the wrapped object reference on add/remove
D. Cache all possible decorator combinations in a lookup table

Solution

  1. Step 1: Understand dynamic add/remove requirement

    Need to add or remove decorators at runtime without subclass explosion or code changes.
  2. Step 2: Identify suitable data structure and pattern modification

    Using a stack to track decorators allows pushing and popping decorators, updating the wrapped object reference accordingly.
  3. Step 3: Evaluate other options

    Inheritance and flags lead to rigidity; caching all combinations is infeasible for many decorators.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Stack structure supports dynamic decorator management efficiently [OK]
Hint: Stack supports dynamic add/remove of decorators [OK]
Common Mistakes:
  • Trying to use inheritance for dynamic behavior
  • Modifying base class breaks open-closed principle
5. If the parking lot system needs to support dynamic pricing based on spot location, time, and vehicle type, which design approach best supports this extensibility without modifying existing classes?
hard
A. Use the Strategy pattern to encapsulate different pricing algorithms and assign them dynamically
B. Add pricing logic directly inside the ParkingSpot class with multiple if-else conditions
C. Hardcode pricing rules in the ParkingLot class for all spot and vehicle combinations
D. Create separate subclasses of ParkingSpot for each pricing rule variant

Solution

  1. Step 1: Identify extensibility needs

    Pricing rules vary by multiple factors and may change frequently.
  2. Step 2: Evaluate design options

    Embedding logic in ParkingSpot or ParkingLot leads to rigid, hard-to-maintain code. Subclass explosion is unmanageable.
  3. Step 3: Recognize Strategy pattern benefits

    Strategy encapsulates pricing algorithms, allowing dynamic assignment and easy extension without modifying existing classes.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Strategy pattern supports flexible, maintainable pricing logic [OK]
Hint: Use Strategy pattern to keep pricing logic flexible and decoupled [OK]
Common Mistakes:
  • Embedding complex logic inside core classes
  • Using inheritance for every pricing variant
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