在构造函数中做了很多坏事吗? [英] 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) 并坚持使用 Dependency Injection (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.
- 我认为将历史编译器缺陷考虑在内来编写新代码并不是一个好主意.如果我们这样做,我们也可以取消 C++11 和所有好的东西.
... 如果您的构造函数需要为其遵守 资源获取即初始化 (RAII) 并且该类不违反 SRP 和 DI 使用得当;然后在构造函数中工作是A-好的!如果您想阻止使用初始化完全失败的类对象,而不是依赖用户检查某些返回值,您甚至可以抛出异常.
... 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屋!