Give an example of a class that follows SRP
A class that follows SRP solves only one task and has only one reason to change.
Below is an example where the responsibility of creating an order is extracted into a separate class, without logging or notifications:
python
class OrderCreator:
def __init__(self, repository):
self.repository = repository
def create(self, order_data):
self._validate(order_data)
return self.repository.save(order_data)
def _validate(self, data):
# validate that order data is correct
if "email" not in data or "items" not in data:
raise ValueError("Invalid order data")Why this class follows SRP
- A single responsibility - creating an order It only validates data and saves the order through the injected repository.
- One reason to change This class only needs to change if the rules for creating or validating an order change.
- No infrastructure responsibilities It does not send emails, does not write logs, does not talk to external systems - all of that is outside its area of responsibility.
- The logic is focused and easy to test It is enough to swap out the repository - and the class can be tested fully in isolation.
Such a class reflects the essence of SRP: one task → one module → one reason to change.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.