Are utility classes allowed with the Single Responsibility Principle (SRP)
-
07-07-2021 - |
题
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:
- Violate SRP as you mentioned because it often takes more than one responsibilities.
- Most of them are static classes, it is not good for test design ability and cannot be mocked.
- 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.
不隶属于 StackOverflow