4

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?

Alex Peck
  • 4,603
  • 1
  • 33
  • 37
Morten
  • 3,778
  • 2
  • 25
  • 45

1 Answers1

7

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.

cuongle
  • 74,024
  • 28
  • 151
  • 206
  • I may be wrong, but i feel utility classes do follow SRP. Since the UtilityClass responsibility is to take input and perform action on the input and provide output. And every function in the class does the same. Hence Utility class does have single responsibility of modifying input and provide output. – Raghav Sharma Nov 03 '17 at 09:35
  • Your arguments are not valid. the 1) is only true if the utility class is badly designed and performs functions out of its scope (as if `Math` were to perform date functions), 2) You don't need to mock implementations, as they usually do well defined procedures which can be tested as easily, parameters can be mocked but there is no need to mock implementation 3) It is not meaningless if you have some repetitive functions that will be used by your 20 modules. If you were to change something you'll need to search for all duplicate codes instead of a focal point. – htafoya Jul 31 '19 at 20:45