简体   繁体   English

在返回值和“回调”之间做出决定时的样式与一致性

[英]Style vs. Consistency when deciding between return value and 'callback'

The code I'm currently re-working works something like this (pre-C++11): 我当前正在重新编写的代码的工作原理如下(C ++ 11之前的版本):

FOO.CPP FOO.CPP

if (CONDITION)
{
    SyncThing thing;
}
else
{
    AysncThing thing;
}

complete(bool isSuccess)
{
    // parses status and clears up
}

where SyncThing and AsyncThing are as follows: 其中SyncThing和AsyncThing如下:

SYNCTHING.CPP 同步CPP

SyncThing::SyncThing()
{
    // some complex synchronous stuff that calls Foo::complete() when done.
}

ASYNCTHING.CPP 异步CPP

AsyncThing::AsyncThing()
{
    // some complex asynchronous stuff that calls Foo::complete() when done.
}

In the interest of not having constructors do complicated stuff and avoiding the non-obvious code path of the constructors calling Foo::complete() when done, I want to remove the complex stuff from SyncThing's constructor and put it in a separate function that's called from Foo.cpp's logic, as follows: 为了不让构造函数做复杂的事情,并避免在完成后避免构造函数调用Foo :: complete()的非显而易见的代码路径,我想从SyncThing的构造函数中删除复杂的东西,并将其放在一个单独的函数中,该函数称为根据Foo.cpp的逻辑,如下所示:

FOO.CPP FOO.CPP

if (CONDITION)
{
    SyncThing thing;
    bool didTheThing = thing.doSomeComplexSyncStuff();       
    complete(didTheThing);
}
else
{
    AysncThing thing;
}

complete(bool isSuccess)
{
    // parses status and clears up
}

I think that makes the code path easier to follow. 我认为这使代码路径更易于遵循。

My questions as as follows: 我的问题如下:

  1. Ignoring AsyncThing, is my bool-return version of the SyncThing better and simpler than having the constructor of SyncThing or SyncThing::doSomeComplexSyncStuff() calling Foo::Complete() when done? 忽略AsyncThing, 我的SyncThing更好更简单布尔回报版本比有SyncThing或SyncThing :: doSomeComplexSyncStuff(的构造函数)调用foo ::完成()的时候做了什么?

  2. Overall, given that the 'callback' style returning is necessary when it comes to AsyncThing, is it better to keep the consistency and do the same for SyncThing, even if the answer to 1. is positive? 总体而言,考虑到AsyncThing,有必要返回“回调”样式,是否最好保持一致性并对SyncThing进行相同处理,即使对1.的回答为肯定?

Thanks very much! 非常感谢!

In my opinion the best Thing would be when you do something like SyncThing.setCompletedFunction(&complete) for SyncThing and AsyncThing . 在我看来,最好的事情是对SyncThingAsyncThing做类似SyncThing.setCompletedFunction(&complete)AsyncThing This makes it clear for both 这两个都清楚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM