现在,我正在阅读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)构造函数
有多么危险。
引用的句子似乎是解决方案,但我不确定确切的含义。
那么,您可以检查一下我的想法是否正确。
首先,他们说将类绑定(bind)在同一包的模块中。
这意味着例如您的系统中有一个包。而且使用与包对应的Module
好不好?那么,基本上你有相同数量的模块和相同数量的包?
其次,您可以看到通过直接实例化的方式对类进行单元测试。
这意味着我们应该使用直接实例化来对类进行单元测试,而不是 Guice
的 Module
?
我认为 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?
是的。无论如何,你应该始终使用包。除了玩具大小的程序之外,不鼓励使用默认包。
我通常希望有一个 org.whatever.foo.some.feature
包,其中包含一个名为 FeatureModule
的模块类(即包的名称 + 模块
,而不是特定的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.
如果直接注入(inject)要测试的内容,就更容易准确地看到正在测试的内容。
当然,您可以使用 guice,但是绑定(bind)存在一定量的“魔法发生在这里”,这可能会隐藏测试中的意外行为。
这适用于单元测试;如果您正在进行集成测试,您可能确实希望使用类似于生产代码的方式,这可能涉及 guice。
关于java - Guice 中构造函数修饰符的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221990/