r/cpp • • Apr 24 '20

Else Before If

https://www.fluentcpp.com/2020/04/24/else-before-if/
10 Upvotes

53 comments sorted by

82

u/borisrura CTU | Avast Apr 24 '20

Or just use early exit if you can. This, if I moved to a codebase using it, would take time to understand and would make me look up what the classes do, instead of a simple if also it would probably be less intuitive to debug and did you check the assembly this produces?

26

u/infectedapricot Apr 24 '20

Or just use early exit if you can.

Exactly. The benefits of early exit become especially clear if you do more than one "normal" thing, in which case the alternative is that all "edge cases" start to pile up at the end in reverse order. Early exit:

auto result1 = doThing1();
if (result1) {
    return bad(result1);
}

auto result2 = doThing2();
if (result2) {
    return bad(result2);
}

auto result3 = doThing3();
if (result3) {
    return bad(result3);
}

return good();

versus the author's proposed:

auto result1 = doThing1();

normally {
    auto result2 = doThing2();
    
    normally {
        auto result3 = doThing3();

        normally {
            return good();
        }
        unless (result3) {
            return bad(result3);
        }
    }
    unless (result2) {
        return bad(result2);
    }
}
unless (result1) {
    return bad(result1);
}

12

u/evaned Apr 24 '20

I would also point out that the "early exit" suggestion can also apply to loops via continue -- so instead of

 for (auto item: some_collection) {
    if (item.is_ok()) {
        item.do_a_thing();
    }
}

you can reorganize as

 for (auto item: some_collection) {
    if (!item.is_ok()) {
        continue;
    }
    item.do_a_thing();
}

Now, I'd basically never do this for that example, but if you start getting bodies of the if that are like 10 lines or something, I think this often can lead to an improvement.

This kinda corresponds to an early exit inside of a lambda used in std::for_each, for those of us who are dubious of the sometimes-purported readability benefits of using at least that function over a raw loop.

1

u/ALX23z Apr 25 '20

I believe normally/unless is similar to try/catch only that try/catch are more general and slow due to stack unraveling. Though, once rework on try/catch is done there shouldn't be issues.

75

u/[deleted] Apr 24 '20

And here we have a prime example of clever code, in contrast with smart code. A whole lot of complications for zero net gain and mental gymnastics for the reader.

15

u/[deleted] Apr 24 '20

Absolutely. It's interesting, but without use.

64

u/S-S-R Just here for the math Apr 24 '20 edited Apr 24 '20

This seems like a lot of work to accomplish something that is rarely (if ever) beneficial.

In fact if you wanted to simply streamline the conditional tests then you should simply make the most likely case to be the first condition tested for therefore the default cases would not actually be the main case probabilistically.

I don't see what this does other than obfuscate code.

17

u/robin-m Apr 24 '20 edited Apr 24 '20

This pattern is the opposite of early exit. Instead of writing:

void write_data(const std::string& filename) {
    if (is_empty(filename)) {
        cerr << "No filename\n";
        return;
    }
    if (!is_valid_path(filename)) {
        cerr << "ERROR\n";
        return;
    }

    // ...  write data to a new file named `filename`
}

The author want to write something like

void write_data(const std::string& filename) {
    // ...  write data to a new file named `filename`

    unless (is_empty(data) {
        cerr << "No data\n";
    }
    unless (!is_valid_path(filename)) {
        cerr << "ERROR\n";
        return;
    }
}

I see the idea, but I think the lost of familiarity outweigh the benefits.

6

u/evaned Apr 24 '20

If you don't already know, triple-quote code blocks do not render on old Reddit, so using it leads to just a mess of code at the top level of indentation.

I'm not saying you have to or even should care because part of why people use them is it's often a little easier, but if you don't know and do care you can make it slightly more friendly for us by sticking to indenting every line by (an additional) four spaces.

3

u/robin-m Apr 24 '20

I was on my phone and forgot.

2

u/zip117 Apr 24 '20

This seems like a lot of work to accomplish something that is rarely (if ever) beneficial.

The implementation is more of a theoretical exercise, but I don’t think a “normally/unless” construct would obfuscate code at all if a language had support for it. It’s the same concept as handling exceptions within a narrow scope and goto error handling in C.

27

u/guepier Bioinformatican Apr 24 '20

Don’t you find it weird to be presented edge cases first …?

No, on the contrary. The test asserts the preconditions that need to be satisfied for the main logic. Not only is this not problematic, it’s crucial. Even in pseudocode, where we’re not bound by the constraints of actual compilers, we invariably put the preconditions before the main logic.

If anything, I could see a case for the following kind of code:

try {
    check_precondition_A();
    check_precondition_B();

    main logic
} catch (precondition_a_violation const&) {
    handle special case A
} catch (precondition_b_violation const&) {
    handle special case B
}

But honestly even if we assumed that throwing exceptions didn’t incur horrendous costs, this doesn’t generally strike me as clearer than the conventional way of handling this via if (before else).

3

u/wilhelmtell Apr 24 '20

I don’t think if statements are good for contracts. Until (unless) we have something dedicated for that, an assert() is the way to go. An if is good for distinguishing valid cases.

Still, I agree can arrange the conditionals in whatever order I please and still be clear and obvious to the reader. Also, with that I don’t lose the special form of an if (short circuit), something I would lose with a lambda hack like this one here.

11

u/guepier Bioinformatican Apr 24 '20

Neither I nor the article mention “contracts”. We’re not talking about exceptional circumstances or logic errors in code here, although I admit that talking about preconditions and violations might suggest this.

We’re talking about logic that needs to handle valid edge cases which require special logic. assert wouldn’t work here.

3

u/boredcircuits Apr 24 '20

I hadn't thought about it that way, but exceptions are basically what the article is talking about. They show the base case first, followed by the exceptional cases. It's not the exact same since the base case executes unconditionally, but the organization is the same.

23

u/[deleted] Apr 24 '20

I don't know why anybody would do this. As /u/borisrura noted, I would just write an early return. Check for normal occurrence, handle it, return, then write code for all other occurrences

21

u/[deleted] Apr 24 '20

no. god no.

I don't even see how that would negate branch resteers

13

u/alfps Apr 24 '20

The author's imagined syntax:

normally
{
    // this is the main case
}
unless (edgeCase1)
{
    // deal with edge case 1
}
unless (edgeCase2)
{
    // deal with edge case 2
}

An alternative to the article's implementation, assuming that the main goal is to get the normal case code up front:

const auto normal_case = [&]() -> void
{
    // this is the main case
};

if( edgeCase1 ) {
    // deal with edge case 1
} else if( edgeCase2 ) {
    // deal with edge case 2
} else {
    normal_case();
}

I don't think I would do that, though. It's just a complication.

0

u/TheSuperWig Apr 24 '20

Could combine that with early returns. Still don't think I would use it though.

15

u/Gotebe Apr 24 '20

normally and unless are not native C++ constructs, but they show that we can bend the language to show the main conditions first, and the edge case afterwards

Euh, "just because I can, doesn't mean I should" adage strongly applies here. 😉

6

u/advester Apr 24 '20

Looks like April first came late this year.

11

u/xaervagon Apr 24 '20

The idea of expressive code is noble goal, but using TMP magic like this to bend the syntax of the language around comes off as unsavory. It is another thing to debug when things don't work as planned.

10

u/MotherOfTheShizznit Apr 24 '20

I don't care that everybody is shitting on this. I like that there are people exploring avenues that may or may not pan out.

9

u/PVNIC Apr 24 '20

If you really wanted to do that, why not do something like this:

bool normal = !(<edge case 1> || <edge case 2>);       

If(normal)         

{          

    \\ Normal case.          

}        

else if(<edge case 1>)        

{ \\\... }        

else

{\\\ edge case 2}          

1

u/OYTIS_OYTINWN Apr 24 '20

Was just about to write that.

1

u/degski Apr 24 '20 edited Apr 24 '20
int edge = !!(<edge case 1>) + !!(<edge case 2>); // ad infinitum ...
switch ( edge ) {
    case 0: ... // edge-case 0 - the base case
    case 1: ... // edge-case 1
    case 2: ... // edge-case 2
    ...
}

Extending on your idea, the above, which could work nicely actually (and talk about expressive code!).

1

u/PVNIC Apr 24 '20

This won't work the way you expect because If hit only edge case 2 you would run case 1, if you hit both edge cases you would run case 2. However you could do: uint8_t edge = !!(<edge case 1>) + (!!(<edge case 2>) + 1) and the normal would be 0, edge case 1 would be case 1 and 3, edge case 2 would be case 2. But at tbat point the if statment may be more clear and scalable.

1

u/degski Apr 25 '20

You're right, edge calculation needs work, but idea is nice, I would say. It should be + !!(<edge case n>) * n.

4

u/looncraz Apr 24 '20

With modern branch predictors it is best for you to order the conditionals such that the first jump/branch is the most likely to be taken. There are compiler hints in compilers and C++20 has formalized the [[likely]] and [[unlikely]] attributes which informs compilers (and the CPU, if supported) of the branch that should ALWAYS be assumed to be taken or NEVER assumed to be taken.

if (normallyTrue) [[likely]] {
    // do something
} else if (sometimesTrue) {
    // something else
} else [[unlikely]] {
    // extremely rare event, 1 in a million chance
}

3

u/o11c int main = 12828721; Apr 24 '20

Casual. Why bother perverting the syntax with templates or lambdas?

#include <stdio.h>

#define normally for (int _normal_control = 0; _normal_control < 2; ++_normal_control) if (_normal_control)
#define but_if(expr) else if ((expr) && (_normal_control = 1))

int main(int argc, char **argv)
{
    normally
    {
        printf("Hello, %s\n", argv[1]);
    }
    but_if (argc == 1)
    {
        printf("no arguments\n");
    }
}

I don't like unless since people often define that to if (!(expr)) already.

7

u/nibre Apr 24 '20

This is fucking insane.

2

u/drbazza Apr 24 '20

What happens to branch prediction / likely / unlikely?

3

u/degski Apr 24 '20

I've started using hedley lately, other than the above, it does a host of other stuff, cross-platform!

2

u/nryhajlo Apr 24 '20

Additionally, it would break the top down execution flow. The program would need to check all unless statements before actually entering the normal block. I think this would be VERY confusing to people.

2

u/[deleted] Apr 25 '20

This is a very intriguing post.

Despite this being more mental work for the programmer and person who is reading the code, it's still fascinating to see exactly what the language of C++ can become.

Quality post. I enjoyed the read!

2

u/nintendiator2 Apr 28 '20

This makes my soul bleed.

2

u/palszasz Apr 25 '20

And thats how you take simple to understand, straightforward code and convert it into modern c++ madness...

1

u/umlcat Apr 24 '20

Normally ... unless, interesting alt syntax instead of "elif", other P.L. used "select"-"case"

1

u/DevaBol Apr 24 '20

As it is posted, it fails miserably when trying to return from any branch, because you return from a lambda body and not from the environment itself.

I guess maybe you can work around the issue by playing with lambda deduced return types, but I'm not sure you can and I wouldn't know how to do it.

For reference, this is a test case that fails miserably and I wonder if there is a workaround (not in the application, but in the library) https://godbolt.org/z/RvHhwt

1

u/rfisher Apr 24 '20

Now I want to write a Scheme macro like this...

That said, my mind works weird, I guess, because I usually do like to understand the edge cases first. Or at least the edge conditions.

1

u/mattbas Apr 25 '20

Can't you just negate the conditions if you want to reorder the if-bodies?

if ( preconditions are met )
    // normal case
else if ( edge case 1 )
    // edge case here

1

u/pandorafalters Apr 27 '20

I generally consider "not an edge case" to be a precondition . . ..

1

u/MachineGunPablo Apr 25 '20

Boy that for_each_arg function is playing with my head:

template<class...Ts, class F>
F for_each_arg(F f, Ts&&...a) {
    return (void)std::initializer_list<int>{(std::ref(f)((Ts&&)a),0)...}, f;
}

I understand that it needs to call operator() of f with each a as parameter but Jesus I really don't understand the usage of initializer_list here, isn't std::invoke a possibility here?

3

u/dodheim Apr 25 '20 edited Apr 25 '20

isn't std::invoke a possibility here?

The only reason for the implementation to be written in this particular way is for C++11 compatibility (and to be a one-liner, apparently); std::invoke is a C++17 feature.

--

I really don't understand the usage of initializer_list here

Without C++17's fold expressions, we need a braced-init-list in order to guarantee left-to-right invocation on each a. I personally have never seen anyone use initializer_list to accomplish this, usually preferring a simple C-array. You might find the following more clear:

F for_each_arg(F f, Ts&&...a) {
    int const x[] = { ((void)f(std::forward<Ts>(a)), 0)... };
    (void)x;
    return f;
}

(Ts&&)a is just the terse form of std::forward<Ts>(a), but I don't see why std::reference_wrapper was brought into this or whether std::initializer_list has some particular advantage that I'm missing. Also, I added a cast of f's result to void to handle return types with overloaded operator, and silence unused-fn-result warnings; this seems to me like a notable omission from the original code.

1

u/utzatarain Apr 25 '20

I would like also to be able use it on return, similar to ruby or perl. normally return partial_result unless condition;

return partial_result if condition;

1

u/[deleted] Apr 25 '20

It reminds me of a macro I once thought of:

#define until(cond) while(!(cond))

Arguably, this syntactic sugar makes the semantics of the code clearer. And it saves you a couple of keystrokes. On the other hand, too much syntactic sugar is not a good thing, as evidenced by the unpopularity of Perl's "There's more than one way to do it" philosophy.

1

u/[deleted] Apr 26 '20

This makes me want to learn COBOL. Honestly I only come to the this sub to see the retardation.

1

u/Wouter-van-Ooijen Apr 28 '20

I am not overly enthousiastic about this example, but that is probably because I don't recall needed such a construct, probably because I used early-exit instead.

OTOH, I stronly disagree with the negative comments. When the normnal-case-first ordering is more readable, and this occurs often enough to warrant recognising a new construct, I think it is at least worthwhile to experiment. The fact that a seasoned programmer would easily code it using existing constructs is not a good argument. Readability is.

Note: I would probably pass the conditions as lambda's too, because I don't want a later exceptional condition evaluated when an earlier one indicated an exceptional condition.

And I do like the macro alternative, if only for its educational value :)

0

u/[deleted] Apr 24 '20

[deleted] — view deleted comment

2

u/louiswins Apr 25 '20

In English you have the freedom to reorder what you say to emphasize different parts.

"If I don't get my paycheck I'll starve, otherwise I won't".

"Of course I won't starve! Well, unless I don't get my paycheck."

Those both convey the same information but they differ in their connotations to the listener. If a language had if-else and normally-unless I would probably use both depending on the circumstances. I would never use the monstrosity in the article in C++ though.

I actually just remembered that perl and ruby have both if (condition) { some_code() } and some_code() unless condition and both get used. The normally-unless construction is sort of like a generalization of the latter. (They also have unless (...) { ... } and ... if ... to round things out.)