做了很多在构造函数不好吗? [英] Is doing a lot in constructors bad?
问题描述
使所有字段 final
是一个好主意,但有时我发现自己在构造函数中做的一切。最近我结束了一个类,在构造函数中实际执行 ,包括读取属性文件和访问数据库。
Making all fields final
is in general a good idea, but sometimes I find myself doing everything in the constructor. Recently I ended up with a class doing actually everything in the constructor, including reading a property file and accessing a database.
这是类是什么,它封装了数据读取,我喜欢创建对象完全初始化。构造函数并不复杂,因为它委托大部分工作,所以看起来很好。
On one hand, this is what the class is for, it encapsulates the data read and I like creating objects completely initialized. The constructor is not complicated at all as it delegates most of the work, so it looks fine.
另一方面,它感觉有点奇怪。此外,在约17:58的这个演讲中,有很多理由不在构造函数中做太多工作。我想我可以通过传递适当的虚拟对象作为构造函数参数来消除这个问题。
On the other hand, it feels a bit strange. Moreover, in this talk at about 17:58 there are good reasons for not doing much work in constructor. I think I can eliminate the problem by passing appropriate dummies as constructor arguments.
问题仍然是:在构造函数中做了很多工作(甚至所有的工作) ?
The question remains: Is doing a lot of work (or even all the work) in constructors bad?
推荐答案
我认为在构造函数中做工作可以...
...只要您不违反单一责任原则(SRP),并坚持使用依赖关系注入(DI)。
我最近一直问自己这个问题。我发现在构造函数中工作的动机是:
I have been asking myself this question too lately. And the motivation against doing work in the constructor that I have found are either:
- 这使得很难测试
- 我看到的所有示例都是未使用 DI 的示例。
- It makes it hard to test
- All examples I have seen have been where DI wasn't used. It wasn't actually the fault of the constructor doing actual work.
- 这基本上违反了 SRP ,而不是
- This is basically a violation of SRP, not a fault of the constructor doing work per say.
- 我认为考虑编译器的历史错误编写新的代码是个好主意。
...如果你的构造函数需要做工作,坚持资源获取是初始化(RAII),并且类不违反 SRP 和 DI 已正确使用;然后在构造函数中做的工作是A-Okay!如果你想防止使用初始化失败的类对象,而不是依靠用户检查一些返回值,你甚至可以抛出异常。
... if your constructor needs to do work for it to adhere to Resource Acquisition Is Initialization (RAII) and the class does not violate SRP and DI is properly used; Then doing work in the constructor is A-Okay! You can even throw an exception if you'd like to prevent usage of a class object whose initialization failed completely instead of relying on the user to check some return value.
这篇关于做了很多在构造函数不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!