Give an example of an SRP violation
An SRP violation occurs when a single class takes on different responsibilities that belong to different layers or aspects of the system. Example:
Example of a class that violates SRP
python
class OrderService:
def create_order(self, order_data):
# business logic for creating an order
self._validate(order_data)
self._save_to_db(order_data)
# send a notification to the customer
self._send_email(order_data["email"])
# write to the log file
with open("orders.log", "a") as f:
f.write(f"Order created: {order_data}\n")
def _validate(self, data):
...
def _save_to_db(self, data):
...
def _send_email(self, email):
...Breaking down the violation
- Business logic
The methods
create_order,_validate,_save_to_dbbelong to the "orders" domain. - Notifications
The
_send_emailmethod belongs to communications - a different responsibility. - Logging
Writing to
orders.logbelongs to infrastructure - a third responsibility.
As a result, the class has three reasons to change:
- the order-creation process changes → the class must be changed;
- the email-notification format changes → the same class must be changed;
- logging requirements change → the same class must be changed again.
This is a direct SRP violation.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.