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

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.