Skip to main content

Examples of Single Responsibility

Single Responsibility Principle (SRP)

Examples

Bad Example: A class that handles both order processing and payment handling.

public class OrderService {
public void processOrder(Order order) {
// Order processing logic
}

public void handlePayment(Payment payment) {
// Payment handling logic
}
}

Good Example: Separate classes for single responsibilities.

public class OrderProcessingService {
public void processOrder(Order order) {
// Order processing logic
}
}

public class PaymentService {
public void handlePayment(Payment payment) {
// Payment handling logic
}
}

Real-World Scenarios

  • E-commerce Application: Separate classes handle order processing and payment services. This ensures that changes in payment logic do not impact order processing.
  • Web Application: User management (e.g., creating and deleting users) and logging are handled by different classes, keeping the code modular and maintainable.
  • Data Processing Pipeline: File operations (reading and writing files) and data processing (transformations, calculations) are managed by separate classes to enhance clarity and maintainability.

By separating the responsibilities into different classes, we adhere to the Single Responsibility Principle. This makes each class more focused, easier to maintain, and more reusable.