定义带依赖的接口的原则是什么?

What's the principle to define an interface with dependencies?

哪个依赖项应该作为参数放在方法签名中,哪个不应该?由于我们有像 spring 这样的 IoC 容器,大多数依赖项都可以通过它注入。

对于java.util.concurrent.Executor

public interface Executor {

    void execute(Runnable command);
}

界面可以是

public interface Executor {

    void execute();
}

另一种情况,在传统的web应用中,一个计数器可能会这样写

public interface CounterManager {

    int query(User user);//user is a runtime information
}

由于 spring 提供了请求范围,User 也可以被注入。

public interface Counter {

    int query();//get user through Injected
}

是否有一些原则或最佳实践来做出选择?谢谢!

Is there some principle or best practice to make the choice? Thanks!

您可以使用 "Coding complexity rule" 作为指导。任何能在短期和长期降低代码复杂性的东西都是好的。引起它的一切都是坏的。

如果您开始使用 DI 容器注入所有内容,您最终会得到一个大小为 Merriam-Webster Dictionary 的 DI 设置文件。

如果事情如此简单,可以作为参数传递给方法,为什么要用 DI 容器使事情复杂化?