I just answered a question related to SRP which made me think: How does SRP stand on utility classes?

By definition utility classes tend to do a lot of things. I can see how gatering related utilities at a single accesspoint is usefull. By SRP standards you cannot implement the utilities in one class. Does that mean that a utility class is a no-no, or does SRP allow it if it is only a facade for multiple classes, each of them adhering to SRP?

有帮助吗?

解决方案

Utility class is considered as anti-pattern:

  1. Violate SRP as you mentioned because it often takes more than one responsibilities.
  2. Most of them are static classes, it is not good for test design ability and cannot be mocked.
  3. The name itself is meaningless, they are often named Helper, Util, Utility or something like that.

To correct:

Devide your utility class to more smaller non-static classes with meaningful-names, each class takes just one responsibility.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top