Enbugger
Enbugger

Reputation: 366

What the briefest way to compose functions with early returns?

I often use the following pattern composing functions that write to parameters given by reference and the other ones that take the same parameter as a constant.

For example:

bool App::Initialize()
{
    Config config;           
    if (!ReadConfig(config))  
        return false;          
    if (!ApplyConfig(config)) 
        return false;          
}

Where the signatures of the methods are:

 bool ReadConfig(Config& config); 
 bool ApplyConfig(const Config& config);    

The approach above requires mentioning config, if and return multiple times. Is there a briefer form of making such type of "chain" calls in c++?

Something like this in pseudocode:

bool App::Initialize()
{
  return build<Configs>().get(&App::ReadConfig).use(&App::ApplyConfig);
}

Upvotes: 1

Views: 64

Answers (1)

Cruz Jean
Cruz Jean

Reputation: 2819

Well if that's all that function does, you could always take advantage of short circuit evaluation of logical operators:

bool App::Initialize()
{
    Config config;
    return ReadConfig(config) && ApplyConfig(config);
}

Upvotes: 3

Related Questions