Skip to content

ES.20, change to a simpler solution in example #9

@peno2

Description

@peno2

I suggest to update an example in rule ES.20.
A little background:
I have already made a suggestion to add a rule advising to use the ternary operator for conditional initialization. That suggestion was turned down by the editors, see issue 1860. Below follows a similar suggestion, but now it not a new rule explicitly promoting the use of the ternary operator.

So, there is an example in rule ES.20 where it is stated that "This cannot trivially be rewritten to initialize i and j with initializers. ".
Actually, in my opinion the code example can be rewritten, maybe not "trivially", but still so the code becomes very simple.
In the example there is some reasoning about using lambdas, but in my opinion it would be good to suggest the simplest possible solution, using the ternary operator. It is important to write simple code, and thus I find this example, as it currently stands, leading inexperienced programmers and others too, in the wrong direction, by not presenting the simplest solution possible. A solution without lambdas or initialization functions.
So here follows my suggested rewrite:

Example
Here is an example that is often considered to demonstrate the difficulty to initialize objects directly at declaration.


widget w1;    // "widget" a type that's expensive to initialize, possibly a large POD
widget w2;

if (cond) {  // bad: w1 and w2 are initialized "late"
    w1 = f1();
    w2 = f2();
}
else {
    w1 = f3();
    w2 = f4();
}

Using the ternary operator '?' this can be rewritten to initialize both w1 and w2 at the time of declaration:

// Good, properly initialized right away, may also be const now, if so desired.
const widget w1 = cond ? f1(): f3();
const widget w2 = cond ? f2(): f4();

Or, as a matter of style, if this communicates the intent better, initialize both 'w1' and 'w2' in one single statement:

using std::pair;
const auto [w1,  w2]  = cond ?  pair{f1(), f2()}:  pair{f3(), f4()};    // C++17

If the condition is more complicated than in the example one could use a lambda ES.28, or even a small function dedicated for the initialization.

Then continue with the text as it was originally, starting from: "Using a value representing "uninitialized" is a symptom of a problem and not a solution:"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions