默认构造函数是否应该将 NULL 传递给另一个构造函数来创建依赖项?
我有一堆具有一组依赖项的类。这个项目的依赖注入将是矫枉过正的,所以目前我们在许多情况下有以下模式:
public MyClass() : this(null, null) {}
public MyClass(Dependancy x, Dependancy y)
{
this.x = x ?? new Dependancy();
this.y = y ?? new Dependancy();
}
我不喜欢这段代码,但我不完全确定为什么。一个原因是它会干扰传入的参数,另一个原因是我可能希望参数为空,并保持为空。
是否有任何充分的理由避免/使用这种模式或任何其他模式,或者它基本上只是个人偏好?
I have a bunch of classes that have a set of dependencies. Dependency Injection for this project will be overkill, so currently we have the following pattern in a number of cases:
public MyClass() : this(null, null) {}
public MyClass(Dependancy x, Dependancy y)
{
this.x = x ?? new Dependancy();
this.y = y ?? new Dependancy();
}
I don't like this code, but I'm not totally sure why. One reason would be the fact that it fiddles with parameters that are passed in, the other is that I might want the parameter to be null, and stay null.
Are there any strong reasons to avoid/use this pattern or any other, or is it basically just personal preference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不喜欢它有两个原因:
You do not like it because of two reasons:
您发布的代码的问题是您正在使用依赖注入,而您只是没有使用控制反转。
MyClass
已将其依赖项注入其中,但如果它们不符合预期,它会假设控制要执行的操作。有几个原因导致这种情况令人不快:MyClass
与较低级别的类Dependency
耦合。MyClass
充当 ServiceLocator,本身就是一种反模式,而且也违反了单一责任原则。MyClass
,其依赖项均设置为Dependency
。正如 @Alessandro Santini 所说,我真的鼓励你放弃这个并使用 DI / IoC 容器。至少摆脱无参数构造函数并强制任何想要构造 MyClass 实例的东西为其提供适当的依赖项。如果给定的依赖项为空,则双参数构造函数应该抛出异常。
The thing with the code you've posted is that you are using dependency injection, you're just not using Inversion of Control.
MyClass
has its dependencies injected into it, but it then assumes control of what to do if they aren't as it expects. There's a few reasons this is unpleasant:MyClass
is coupled to the lower level classDependency
.MyClass
is acting as a ServiceLocator, which in itself is an anti-pattern, but also violates the Single Responsibility Principle.MyClass
with its dependencies both set toDependency
.As @Alessandro Santini says, I'd really encourage you to scrap this and use a DI / IoC container. At the very least get rid of the parameterless constructor and force anything which wants to construct a
MyClass
instance to supply it with appropriate dependencies. The two-argument constructor should then throw exceptions if the dependencies it's given are null.