Examples of Single Responsibility
Single Responsibility Principle (SRP)
Examples
Bad Example: A class that handles both order processing and payment handling.
- Java
- JavaScript
- Python
public class OrderService {
public void processOrder(Order order) {
// Order processing logic
}
public void handlePayment(Payment payment) {
// Payment handling logic
}
}
class UserService {
log(message) {
// Logging logic
}
createUser(user) {
// User creation logic
}
deleteUser(userId) {
// User deletion logic
}
}
class FileManager:
def read_file(self, file_path):
# File reading logic
def write_file(self, file_path, data):
# File writing logic
def process_data(self, data):
# Data processing logic
Good Example: Separate classes for single responsibilities.
- Java
- JavaScript
- Python
public class OrderProcessingService {
public void processOrder(Order order) {
// Order processing logic
}
}
public class PaymentService {
public void handlePayment(Payment payment) {
// Payment handling logic
}
}
class LoggingService {
log(message) {
// Logging logic
}
}
class UserService {
createUser(user) {
// User creation logic
}
deleteUser(userId) {
// User deletion logic
}
}
class FileService:
def read_file(self, file_path):
# File reading logic
def write_file(self, file_path, data):
# File writing logic
class DataService:
def process_data(self, data):
# Data processing 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.