我应该注入执行算法所需的对象吗?我应该注入一切吗? [英] Should i inject Objects needed for execution of an algorithm? Should i inject everything?

查看:65
本文介绍了我应该注入执行算法所需的对象吗?我应该注入一切吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我在文档中错过了它,但是我想知道我应该如何处理帮助对象?

Maybe i missed it in the documentation but i'm wondering how i should handle "helper Objects"?

代码示例:

public Path dijkstra(Node startNode, Node endNode) {
    Set<Node> nodesToInspect = new HashSet<Node>();  // should this Object be injected?
    Path path = new Path();  // and this one?

    while (!nodesToInspect.isEmpty()) {
        // some logic like:
        path.add(currentNode);

    }

    return path;
}

我应该注入所有内容还是应该在某个时候说算法知道最好的是什么?
我应该尝试消除所有新内容吗?还是某些对象创建很好,例如HashSet,ArrayList等API类。

Should i inject everything or should i say at some point that the algorithm "knows" best what it needs? Should i try to eliminate every "new"? or are some object creations fine, for example API classes like HashSet, ArrayList, etc.

推荐答案

在替换简单的<$之前具有依赖项注入的c $ c> new ,您需要问自己 为什么我要这样做? ...它有什么真正的好处?。如果答案是我不知道或什么都不知道,那您就不应该。

Before you replace a simple new with dependency injection, you need to ask yourself "why am I doing this?" ... "what real benefit does it have?". If the answer is "I don't know" or "nothing", then you shouldn't.

在这种情况下,使用DI并没有真正的好处在示例代码的第一种情况下。不需要其他任何方法来了解内部集的表示方式……甚至不需要知道它的存在。

In this case, I can see no real benefit in using DI in the first cases in your example code. There is no need for anything outside of that method to know about how the internal set is represented ... or even to know that it exists.

您应该考虑的另一个问题请问是否有一种更简单,更明显的方法来实现目标。例如,对 path 变量使用DI的(最可能的)目的是允许应用程序使用不同的 Path 类。但是,执行此操作的简单方法是将 Path 实例作为显式参数传递给 dijkstra 方法。您甚至可以使用重载来使其变得更美味。例如

The other question you should ask is whether there is a simpler, more obvious way of achieving the goal. For example, the (most likely) purpose of using DI for the path variable is to allow the application to use a different Path class. But the simple way to do that is to pass a Path instance to the dijkstra method as an explicit parameter. You could even use overloading to make this more palatable; e.g.

public Path dijkstra(Node startNode, Node endNode) {
    return dijkstra(startNode, endNode, new Path());
}

public Path dijkstra(Node startNode, Node endNode, Path path) {
    ...
}

最后要考虑的是,DI(在Java中)涉及一定程度的反射,并且不可避免地要比使用<$ c的经典方法昂贵。 $ c> new 或工厂对象/方法。如果您不需要直接投资的额外灵活性,则不必为此付费。

The final thing to consider is that DI (in Java) involves reflection at some level, and is inevitably more expensive than the classical approaches of using new or factory objects / methods. If you don't need the extra flexibility of DI, you shouldn't pay for it.

我刚刚注意到您要引用的两个变量是局部变量。我不知道任何允许您注入局部变量的DI框架...

I just noticed that the two variables you are referring to are local variables. I'm not aware of any DI framework that allows you to inject local variables ...

这篇关于我应该注入执行算法所需的对象吗?我应该注入一切吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆