How do you define a Single Responsibility?

前端 未结 13 1791
醉酒成梦
醉酒成梦 2021-01-30 09:23

I know about \"class having a single reason to change\". Now, what is that exactly? Are there some smells/signs that could tell that class does not have a single responsibility?

13条回答
  •  礼貌的吻别
    2021-01-30 09:38

    Martin's Agile Principles, Patterns, and Practices in C# helped me a lot to grasp SRP. He defines SRP as:

    A class should have only one reason to change.

    So what is driving change?

    Martin's answer is:

    [...] each responsibility is an axis of change. (p. 116)

    and further:

    In the context of the SRP, we define a responsibility to be a reason for change. If you can think of more than one motive for changing a class, that class has more than one responsibility (p. 117)

    In fact SRP is encapsulating change. If change happens, it should just have a local impact.

    Where is YAGNI?

    YAGNI can be nicely combined with SRP: When you apply YAGNI, you wait until some change is actually happening. If this happens you should be able to clearly see the responsibilities which are inferred from the reason(s) for change.

    This also means that responsibilities can evolve with each new requirement and change. Thinking further SRP and YAGNI will provide you the means to think in flexible designs and architectures.

提交回复
热议问题