The Single Responsibility Principle (SRP) is one of the core principles of object-oriented programming. It states that a class should have only one reason to change, meaning it should have only one job or responsibility.
Consider a class that handles both user authentication and logging user activity:
class UserManager { void authenticateUser(String username, String password) { // Authentication logic } void logUserActivity(String activity) { // Logging logic } }
This violates SRP because the class has more than one responsibility. To fix this, separate these responsibilities into different classes:
class Authenticator { void authenticate(String username, String password) { // Authentication logic } } class ActivityLogger { void log(String activity) { // Logging logic } }
By following SRP, you ensure that each class is focused on a single responsibility, making your codebase easier to maintain and extend.