简体   繁体   中英

Helper Classes and Unit Testing

When writing code that happens to be common among several class files, I tend to place them in a helper file.

Should the helper or utility class be injected to the classes where it is needed? Or better to simply have a reference to it "Composition"?

Regards

Your reasons why to choose Composition vs Inheritance should be the well known SOLID principles. Then, "favour composition over inheritance" is a consequence of them, IMO.

IMO you have an Utility class when

  • it is static (as Saurabh said);
  • tasks are not related to a particular domain, but related to raw data (for example an utility to reverse lists);
  • its functions are without side effects;
  • there are no alternative implementations of its functions.

Anyway, with C# extensions, now it's rare to create an utility class.

With an utility class you don't need to inject it (it is static and testable). If, instead, you have composition, the dependency inversion principle states that you should "depend upon abstractions, not concretions", so you can leave the container to inject your abstractions.

Better make it as a Utility class which is a static class.

Dependency is some what closely related to the particular class but in your scenario, I would say you need a utility class.

I'd say you don't need the sophistication of injection unless you help multiple flavours of helper class, each doing the same thing in a slightly different way. I'd say composition is reasonable; you could alternatively make it a utility or toolkit static class, which might make your code a little more explicit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM