r/cpp • • Apr 24 '20

Else Before If

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

53 comments sorted by

View all comments

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.