
The OCP says that to add new features, the classes must be extended (open) instead of modified (close). Now this does not sound practical because every class would evolve relatively to the business it represents. That means we should not introduce changes to a class to add new features/ functionality to it. Singletons are often regarded as opposite of SRP because they quickly become God objects doing too many things (Swiss knife) and introducing too many hidden dependencies into a system.Ī class in a system must not be open to any changes, except bug fixing. This means in a longer run the codebase remains flexible and adoptive to changes. SRP might increase total number of classes in a module but it also increases their simplicity and reusability.
#UNCLE BOB SINGLE RESPONSIBILITY PRINCIPLE CODE#
It means a piece of code should only have one responsibility related to the business: An Entity service should only be concerned about handling entities and not anything else like database handlings, logging, handling sub entities directly (like saving employee address explicitly) etc. Now the class care less about how the database is handled and more about Employee, its true purpose.Īlso note that, SRP does not mean a structure/ class will only have a single function/ property etc. It also ensures that everything is doing their job and their job only. This makes the code a bit cleaner and maintainable. We have removed the database handling details from the EmployeeService class. Let’s KISS (keep it simple, stupid) it a bit.ĭb = Database.Get() // or a constructor etc. It’s like a Swiss knife it looks easy but very rigid and inextensible. Because of baked in database handling details, the EmployeeService has become rigid and harder to reuse or extend for multiple databases, for example. The database handling should not be a responsibility of this class. The EmployeeService has too much responsibilities. Using (var db = new ()) // or some SINGLETON or factory call, Database.Get()Īll looks good yes? There are genuine issues with this code. The more a piece of code is doing, or trying to do, the more fragile, rigid, and difficult to (re)use it gets. should not have more than one responsibility in a system. “There should not be more than one reason for something to exist.”Īs the name suggest, a module/ class etc. – S – Single Responsibility Principle – SRP

We will discuss SOLID one by one and try to relate each of them with the underline problems and how they try to solve them. They mainly address dependencies and tight coupling. SOLID acronym was popularized by Robert Martin as generic design principles dictated by common sense in OOP. The SOLID principles address those dependency issues in OOP. The shared modules and tight coupling leads to dependency issues in design. We have discussed STUPID issues in programming.
