Design Patterns: S.O.L.I.D. Single Responsibility Principle

Limiting Class Scope

As part of the S.O.L.I.D. design principles, the Single Responsibility Principle (SRP) ensures each class should only have one responsibility.

This principle proactively ensures classes begin with a narrow focus, preventing future changes from affecting other parts of the application.

In my previous article OOP: Class Design, I illustrated how a class is modeled after a real-world objects with its attributes (data) and behaviors (methods).

Maintainable & Flexible

However, for each behavior attributed to the class, that represents another potential reason why that class might need to change.

Instead of a large class template from which to create objects, I’ll define an interface for users desiring employee functionality with very specific behavior defined. This interface ensures all classes which inherit it, must provide their implementation details for each method defined in the interface. This defines a contract between the interface and its users and represents functionality which must be implemented.

In the examples above, I created a template for defining EmployeeTest objects, which inherits the IEmployee interface, instantiated an EmployeeTest object whose class inherits the IEmployee interface. Note: I can define the object variable using its interface.

Following this principle results in many smaller classes with cleaner, more understandable code, which means its less fragile to change.

For example, if an employee supervisor needed to conduct a performance review of a subordinate, I could define a new interface to inherit providing a signature for that functionality. I don’t need to change the existing IEmployee interface or any classes which inherit it. In other words, new functionality may be added to the codebase without affecting exsiting code.

To illustrate this benefit, I’ll define a new interface for IEmployeeSupervisor, EmployeeSupervisorTest class template for instantiating objects, an example object being instantiated-note the use of the interface for defining the object variable, and the example result.

To recap, using the SRP ensures objects exist with only one responsibility or purpose and any changes may be integrated without affecting other parts of the application.