How do you define a Single Responsibility?

前端 未结 13 1773
醉酒成梦
醉酒成梦 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:27

    I've also been trying to get my head around the SOLID principles of OOD, specifically the single responsibility principle, aka SRP (as a side note the podcast with Jeff Atwood, Joel Spolsky and "Uncle Bob" is worth a listen). The big question for me is: What problems is SOLID trying to address?

    OOP is all about modeling. The main purpose of modeling is to present a problem in a way that allows us to understand it and solve it. Modeling forces us to focus on the important details. At the same time we can use encapsulation to hide the "unimportant" details so that we only have to deal with them when absolutely necessary.

    I guess you should ask yourself: What problem is your class trying to solve? Has the important information you need to solve this problem risen to the surface? Are the unimportant details tucked away so that you only have to think about them when absolutely necessary?

    Thinking about these things results in programs that are easier to understand, maintain and extend. I think this is at the heart of OOD and the SOLID principles, including SRP.

提交回复
热议问题