Does implementing multiple interfaces violate Single Responsibility Principle?

前端 未结 3 2106
轻奢々
轻奢々 2021-02-08 01:22

From Wikipedia:

Single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-08 01:30

    Maybe, but not necessarily.

    An interface is not a responsibility. There's a very powerful mode of architecture which views interfaces as defining the role the object may play in the application.

    Think of what that means. You can have a Person class with all sorts of interfaces (let's use a .net convention for naming)

    class Person : IAmAStudent, IDrawSocialSecurity, IAmACitizen {
       public SocialSecurityNumber getSocialSecurityNumber() {
          return this.ssn;
       }
       private SocialSecurityNumber ssn;
       public Person(SocialSecurityNumber ssn) { this.ssn = ssn; }
    }
    

    Now obviously this cannot violate SRP. It clearly has only one reason for change - if the relationship between people and social security numbers changes. Yet the object implements many interfaces and plays several roles in the application.

    Now if you're implementing multiple interfaces that expose different functionality you might be violating SRP but that can be a bit of a judgement call as well. Single Responsibility Principle is a great rule of thumb for achieving loose coupling, but that's not the only ideal in town. There's also high cohesion which states that related code should live together. The two are fundamentally at odds (though there is often ways to achieve good balance). So you might reasonably make a choice in the direction of one over another and decide consciously to violate SRP.

    Ultimately, SRP and all the SOLID rules are more about making sure you think along certain lines, not that you follow them blindly every time.

提交回复
热议问题