

But you have to be careful if you put code together that seems to be equal. Conclusionĭuplicate code may be a reason to think of SRP violation. Another time another developer has to change the local part check for one case and he does not check if all other usages will be correct under the new implementation. A developer extracts the code into one central method because it looks technically equal. a local part check for an email address was implemented at different locations of your code base. This happens if technically savvy developers try to reduce code duplication without consider semantics.Į.g. If a functional requirement occurs and you produce an unintentional side effect in another code fragment you violate the SRP. This often happens if a developer does not know that some logic already exists that will solve a probem for him and he develops it once again. If a functional requirement occurs and you have to change two code fragments for the same reason you violate the SRP.

Once you think it violates SRP you can make a thought experiment (coordinated with your business people) your code has to pass to verify your assumption. The problem is (with all SOLID principles) it's not about applying them, it's about identifying a violation them. Single Responsibility has something to say about semantic redundancy and false semantic cohesion of code fragments (modules, classes, methods functions). How can you tell what responsibility should be in a separate class? However when it comes to animate objects like dog it becomes not so evident what methods are different in nature.įunction run($speed, $distance, $direction) (

When we talk about objects inanimate objects its easy to see compile report and print report is two different responsibilities.
UNCLE BOB SINGLE RESPONSIBILITY PRINCIPLE HOW TO
Is there a rule or general guideline on how to define responsibility of methods in class? Is greater danger that the printing code will break if it is part of Continuing with the foregoingĮxample, if there is a change to the report compilation process, there The reason it is important to keep a class focused on a single concern It would be a bad design to couple two things that changeįor different reasons at different times. Separate responsibilities, and should therefore be in separate classes Principle says that these two aspects of the problem are really two These two things change for very differentĬauses one substantive, and one cosmetic. Imagine such a module can be changed for two reasons. As an example, consider a module that compiles and prints a All its services should be narrowly aligned with that responsibilityĬlass or module should have one, and only one, responsibility. class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. From Wikipedia on Single responsibility principle SoC
