[英]dependecy injection and unit testing - static helper methods or private instance methods
From unit testing and dependency injection point of view, what's the usual adopted norm when it comes to helper methods? 从单元测试和依赖注入的角度来看,在辅助方法方面通常采用的规范是什么?
Here is my example situation: 这是我的示例情况:
public class GoodiesController : Controller
{
private IMyContext _context;
public GoodiesController(IMyContext context)
{
_context = context
}
public async Task<IAction> GetThoseGoodies()
{
if(YouLikeThemThisWay(Request.Path))
{
var result = await _context.GoGetThemThisWay()
} else { }
}
My question is am I better off with YouLikeThemThisWay(string path)
as a static helper in some class or as a private instance method? 我的问题是,我最好将
YouLikeThemThisWay(string path)
作为某个类中的静态助手或作为私有实例方法吗? Assuming I might have a couple of the likes of YouLikeThemThisWay
? 假设我可能有几个像
YouLikeThemThisWay
的喜欢?
It really depends on what your YouLikeThemThisWay(string path)
method does. 这实际上取决于你的
YouLikeThemThisWay(string path)
方法的作用。 My rules for using a static method or as follows: 我使用静态方法的规则如下:
Basically, small helper functions that are easily tested and don't affect state or usually OK to make static. 基本上,小辅助函数很容易测试,不会影响状态或通常可以静态。 If there is state involved, the routine requires a dependency that you would normally inject, or the routine is making IO or IPC calls then do not make it static.
如果涉及到状态,则例程需要您通常会注入的依赖项,或者例程正在进行IO或IPC调用,然后不要使其静态。
One caveat to the dependency issue is technically you could use method injection to handle the dependencies, but I like to keep it simple. 对依赖性问题的一个警告是技术上你可以使用方法注入来处理依赖项,但我喜欢保持简单。 Your method is probably OK to be static.
你的方法可能是静态的。
Reuse is a big factor in statics too. 重用也是静力学中的一个重要因素。 If the routine will only be used in one class, it may be pointless to make static.
如果例程只在一个类中使用,那么静态化可能毫无意义。 Most of my static methods live in helper classes that are easily accessed anywhere.
我的大多数静态方法都存在于任何地方都可以轻松访问的辅助类中。
EDIT: Note that I usually require most or all of those five rules to favor statics in order for me to even consider making something static. 编辑:请注意,我通常要求这五条规则中的大部分或全部都支持静态,以便我甚至考虑制作静态的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.