What is the One Class, One Responsibility Principle?

后端 未结 5 2028
广开言路
广开言路 2021-01-12 22:14

I would like to learn about the One Class, One Responsibility principle. I have found some articles about it, but without examples. It would help me if you can giv

5条回答
  •  误落风尘
    2021-01-12 22:43

    On the principle's aspect of not mixing responsibilities.

    If you have an InvoiceProcessor class that handles an invoice, does calculations by business rules, generates a PDF with the invoice, processes the database with registering extra bonus points to the seller, then you have a clear case of needing separation of concerns. In this case a clear separation or even delegation to other classes is due.

    But One Class - One Responsibility is even more subtle and hideous. If you have to provide a solution to invoice processing, and have several goals to fulfil like those bonus points, you can have a violating function that serve several goals: calculate bonus points for seller and discount of customer.

    On a smaller scale: if you have a class with its data structures, like a priority queue or whatever, and at the same time mix it with data structures for caching a part, using say a List and a Map, then you are at some spots manipulating data for different concerns, maybe even addressing inside the cache list, so that the data structures become intertwined. If you then have a function that changes priority and alters the caching state it will get difficult to understand the processes in some future.

    I often encounter violations where some different aspects need to be implemented, and they are done in one class. The API then has calls with different abstraction levels, or a difficult semantic.

提交回复
热议问题