Difference between Single Responsibility Principle and Separation of Concerns

后端 未结 13 1370
-上瘾入骨i
-上瘾入骨i 2020-12-07 15:20

What is the difference between Single Responsibility Principle and Separation of Concerns?

13条回答
  •  無奈伤痛
    2020-12-07 15:54

    The Single Responsibility Principle and Separation of Concerns are really the same thing.

    Sure you can get bogged down in an academic discussion trying to tease out some kind of difference between the two, but why? For all intents and purposes they describe the same thing. The biggest problem is people get so caught up in wanting to know exactly what a "concern" and "responsibility" are, that they perhaps miss the important idea behind SRP and SoC.

    That idea is simply to split your codebase into loosely coupled isolated parts. This allows multiple developers to work on different parts without affecting each other, it also allows a single developer to modify one isolated part without breaking another.

    This is applied at the module level, eg MVC is an architectural pattern promoting SRP and SoC. The codebase is split out into isolated models, views and controllers. That way the modification of a view can be done independently of a model. Two two aren't horrifically intertwined.

    At a lower level this should be applied to classes too. Instead of putting dozens of methods in a single class, split the code out into several. For the same reasons.

    Also even at a method level, split large methods out into smaller methods.

    In principle. SRP is a principle, not a rule, so you don't have to (read: can't/shouldn't) follow it religiously to the extreme. It doesn't mean going too far and having only one seven line method in each class for example. It just means a general principle of splitting out code into isolated parts. The point is it will lead to a better codebase and more stable software.

提交回复
热议问题