简体   繁体   English

辅助类和单元测试

[英]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.您选择组合与继承的原因应该是众所周知的 SOLID 原则。 Then, "favour composition over inheritance" is a consequence of them, IMO.然后,“有利于继承而不是继承”是他们的结果,IMO。

IMO you have an Utility class when IMO 你有一个 Utility 类

  • it is static (as Saurabh said);它是静态的(如 Saurabh 所说);
  • 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.无论如何,有了 C# 扩展,现在很少会创建实用程序类了。

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.您也可以将其设为实用程序或工具包静态类,这可能会使您的代码更加明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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