How do you define a Single Responsibility?

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

    The Single Responsibility Principle

    There are many obvious cases, e.g. CoffeeAndSoupFactory. Coffee and soup in the same appliance can lead to quite distasteful results. In this example, the appliance might be broken into a HotWaterGenerator and some kind of Stirrer. Then a new CoffeeFactory and SoupFactory can be built from those components and any accidental mixing can be avoided.

    Among the more subtle cases, the tension between data access objects (DAOs) and data transfer objects (DTOs) is very common. DAOs talk to the database, DTOs are serializable for transfer between processes and machines. Usually DAOs need a reference to your database framework, therefore they are unusable on your rich clients which neither have the database drivers installed nor have the necessary privileges to access the DB.

    Code Smells

    • The methods in a class start to be grouped by areas of functionality ("these are the Coffee methods and these are the Soup methods").

    • Implementing many interfaces.

提交回复
热议问题