对“initialize()”的参数方法而不是构造函数 [英] Arguments against "initialize()" method instead of constructors

查看:129
本文介绍了对“initialize()”的参数方法而不是构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前负责查找我们的代码库中的所有不良做法,并说服我的同事修复违规代码。在我的spelunking中,我注意到很多人在这里使用以下模式:

I'm currently in charge of finding all bad practices in our code base and to convince my colleagues to fix the offending code. During my spelunking, I noticed that many people here use the following pattern:

class Foo
{
  public:
    Foo() { /* Do nothing here */ }
    bool initialize() { /* Do all the initialization stuff and return true on success. */ }
    ~Foo() { /* Do all the cleanup */ }
};

现在我可能错了,但对我来说 initialize code>方法事情是可怕的。我相信它取消了构造函数的整个目的。

Now I might be wrong, but to me this initialize() method thing is awful. I believe it cancels the whole purpose of having constructors.

当我问我的同事为什么做这个设计决定时,他们总是回答他们没有选择,因为你可以' t退出构造函数而不抛出(我猜他们认为抛出是总是坏的)。

When I ask my collegues why this design decision was made, they always answer that they have no choice because you can't exit a constructor without throwing (I guess they assume throwing is always bad).

我没能说服他们到目前为止,可能缺少有价值的参数...所以这里是我的问题:我是对的,这个结构是一个痛苦,如果是,你看到什么问题吗?

I failed to convince them so far and I admit I may lack of valuable arguments... so here is my question: Am I right that this construct is a pain and if so, what issues do you see in it ?

谢谢。

推荐答案

单步执行(构造函数)初始化和两步)初始化是有用的模式。我个人觉得排除任何一个都是一个错误,虽然如果你的约定禁止使用例外完全,那么你禁止单步初始化的构造函数可能会失败。

Both single step (constructor) initialisation and two step (with an init method) initialisation are useful patterns. Personally I feel that excluding either is a mistake, although if your conventions prohibit use of exceptions entirely then you prohibit single step initialisation for constructors that can fail.

一般我喜欢单步初始化,因为这意味着你的对象可以有
更强的不变量。当我认为对象能够以未初始化状态存在时,我只使用两步初始化。

In general I prefer single step initialisation because this means that your objects can have stronger invariants. I only use two step initialisation when I consider it meaningful or useful for an object to be able to exist in an "uninitialised" state.

两步初始化有效为了使对象处于未初始化状态 - 所以每个与该对象一起工作的方法都需要知道并正确处理它可能处于未初始化状态的
事实。这类似于使用指针,其中假定指针不为NULL的形式不好。相反,如果你在你的构造函数中做所有的初始化,并且失败了异常,你可以添加对象总是初始化到你的不变式列表,因此变得更容易和更安全
做出关于状态的假设对象。

With two step initialisation it is valid for your object to be in an uninitialised state - so every method that works with the object needs to be aware of and correctly handle the fact that it might be in an uninitialised state. This is analogous to working with pointers, where it is poor form to assume that a pointer is not NULL. Conversely, if you do all your initialisation in your constructor and fail with exceptions than you can add 'the object is always initialised' to your list of invariants, and so it becomes easier and safer to make assumptions about the state of the object.

这篇关于对“initialize()”的参数方法而不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆