Does the Single Responsibility Principle work in OOP?

前端 未结 7 1084
面向向阳花
面向向阳花 2020-12-03 15:17

I am struggling to understand how the Single Responsibility Principle can me made to work with OOP.

If we are to follow the principle to a tee, then are we not left

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 16:10

    I tend to think of the Single Responsibility Principle (and really a lot of the rules of thumb, patterns, and models) as a general way of thinking about problems. It's meant to guide you toward improvements to your code, but not necessarily prescribe exactly what a solution looks like. Because ultimately software design is a wicked and subjective problem.

    I don't think that SRP should always lead to a bunch of single function classes. Though these may sometimes occur if you have some complex logic that you want to abstract away. In general, though, you should trend toward classes with highly cohesive functionality where methods:

    1. Are all related to the same abstraction(s)

      • Don't have a mish-mash of functionality that isn't related to each other in the same class.
      • Keep things like business logic separate from UI separate from I/O
    2. Share common dependencies

      • Related functionality usually has related dependencies.
      • I usually consider breaking up a class when I start getting more than around 7 dependencies. Often there's a class I can extract to move a few of the dependencies into a more cohesive unit.
    3. All operate at the same level of abstraction

      • Your abstractions should be hierarchical; some classes should orchestrate other classes to accomplish a workflow. Other classes will handle the specific implementation-level details.
      • Avoid having orchestration-style classes getting into the nitty-gritty. You don't want detailed operations to live side by side (in the same function or even the same class) with abstractions of more complex operations.

    You actually want to try to group as much functionality as you can, while maintaining the above conditions and keeping in mind how understandable your abstraction is. Ultimately the goal of the Single Responsibility Principle is to help manage complexity and make the code more understandable.

提交回复
热议问题