How do you define a Single Responsibility?

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

    Well, this principle is to be used with some salt... to avoid class explosion.

    A single responsibility does not translate to single method classes. It means a single reason for existence... a service that the object provides for its clients.

    A nice way to stay on the road... Use the object as person metaphor... If the object were a person, who would I ask to do this? Assign that responsibility to the corresponding class. However you wouldn't ask the same person to do your manage files, compute salaries, issue paychecks, and verify financial records... Why would you want a single object to do all these? (it's okay if a class takes on multiple responsibilities as long as they are all related and coherent.)

    • If you employ a CRC card, it's a nice subtle guideline. If you're having trouble getting all the responsibilities of that object on a CRC card, it's probably doing too much... a max of 7 would do as a good marker.
    • Another code smell from the refactoring book would be HUGE classes. Shotgun surgery would be another... making a change to one area in a class causes bugs in unrelated areas of the same class...
    • Finding that you are making changes to the same class for unrelated bug-fixes again and again is another indication that the class is doing too much.

提交回复
热议问题