大型初始化列表的缺点?
在我的雇主,我们的政策是在构造函数中使用初始化列表,因为它更有效。
但是,我正在开发一个具有 45 个需要初始化的数据成员的类。根据策略,这必须在构造函数的初始化列表中完成。
除了可读性之外,大的初始化列表还有什么缺点?
At my employer, it is policy that we use initialization lists in the constructor because it is more efficient.
However, I am developing a class that has 45 data members requiring initialization. Per the policy, this would have to be done in an initialization list in the constructor.
Other than readability, what would be the disadvantage to a large initialization list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在多个物理源代码行上格式化成员初始值设定项列表,这样就不会出现可读性问题。
显然,更大的问题是您的类有 45 个数据成员。没有什么能让使用这样的类变得特别容易。
我认为可读性不低于:
You can format a member initializer list over multiple physical source lines so there doesn't have to be a readability issue.
The larger issue is obviously the fact that you have classes with 45 data members. Nothing is going to make working with such classes particularly easy.
I argue is no less readable than:
我认为可能值得退后一步来理解为什么您的类有 45 个数据成员。这通常表明您的类正在做太多事情,并且有太多单独的职责,这将使该类随着时间的推移很难维护。
听起来您可能需要将您的类分解为单独的功能部分,并将“控制器”类委托给子类。这将大大降低代码的复杂性。
I think it might be worth taking a step back to understand why your class has 45 data members. This is usually a sign that your class is doing too many things, and has too many separate responsibilities that is going to make this class very hard to maintain over time.
It sounds like you may need to break your class into separate functional pieces and have the 'controller' class delegate to subclasses. This is going to decrease the complexity of your code dramatically.
这似乎是众所周知的反模式God object。 Wiki 引用:
在面向对象编程中,God 对象是一个知道太多或做太多事情的对象。< /a>
请找到一种方法来重新考虑您的设计,将上帝对象的成员分组为更小的结构和具有自己的初始化过程的对象。
因此,“大的初始化列表有什么缺点?(与小的初始化列表相比)”这个问题的答案可能是“它很大,所以可能是一种不好的样式。
”对于“大型初始化列表有什么缺点?(与大型构造函数体相比)”这个问题的答案可能是“无”,因为初始化最好在列表中完成,而不是在正文,但可读性和维护成本相同(如 为我)。
It seems like well known anti-pattern God object. Wiki citation:
In object-oriented programming, a God object is an object that knows too much or does too much.
Please find a way to reconsider your design to group members of the god object into smaller structures and objects with their own initialization procedures.
So an answer to the question "what would be the disadvantage to a large initialization list? (comparing to a small one)" could be "It is large, so possibly it is a bad style."
An answer to the question "what would be the disadvantage to a large initialization list? (comparing to a large constructor body)" could be "none", because initialization better be done in the list, not in the body, but readability and a cost of maintenance the same (as for me).
有些优化会失败,我怀疑这样的构造函数的内联将不起作用。
不管怎样:45 个数据成员听起来很多。你能将它们分组为如此聚合的对象吗?
Some optimizations will fail, I suspect that inlining of such a constructor will not work.
Either way: 45 Data members sound a lot. Can you group them so aggregated Objects?