Guice 中构造函数修饰符的最佳实践

Best practice for modifiers of constructor in Guice

现在,我正在阅读 Guice's official document. 他们说

As a correction, simply limit the visibility of both your implementation classes, and their constructors. Typically package private is preferred for both, as this facilitates:

binding the class within a Module in the same package

unit testing the class through means of direct instantiation

As a simple, mnemonic remember that public and @Inject are like Elves and Dwarfs: they can work together, but in an ideal world, they would coexist independently.

看了文档才知道public constructor有多危险。 引用的句子似乎是解决方案,但我不确定确切的含义。 所以,你能不能看看我的想法对不对。

首先,他们说 将 class 绑定到同一包中的模块中 。 这意味着例如您在系统中有一个包。而且用一个Module对应的包好不好?所以,基本上你有相同数量的 Modules 和相同数量的包裹?

其次,您可以看到通过直接实例化对class进行单元测试。 这意味着我们应该使用直接实例化对 class 进行单元测试,而不是 GuiceModule? 我认为 Guice 对测试也很有用,尤其是他们所说的单元测试。

我有点迷糊,谁能帮我解释一下?

First, they say binding the class within a Module in the same package. This means for example you have a package in a system. And it is good to use a Module corresponding with the package? So, basically you have the same number of Modules and same number of packages?

是的。无论如何你应该总是使用包。除 toy-sized 程序外,不鼓励使用默认包。

我通常希望有一个 org.whatever.foo.some.feature 包,其中包含一个名为 FeatureModule 的模块 class(即包的名称 + Module,而不是具体 FeatureModule).

Second, you can see unit testing the class through means of direct instantiation. This means we should do unit testing a class using direct instantiation, not Guice's Module? I think Guice is also useful for a testing, especially unit testing as they said.

如果您直接注入要测试的东西,就更容易准确地看到您在测试什么。

当然,您可以使用 guice,但是绑定有一定数量的 "magic happens here",可以隐藏测试中的意外行为。

这适用于单元测试;如果您正在进行集成测试,您可能确实希望使用与您的生产代码接近的东西,这可能涉及 guice。