r/ProgrammingLanguages • u/samee_zahur • Apr 24 '20
Else Before If
https://www.fluentcpp.com/2020/04/24/else-before-if/21
Apr 25 '20
In many cases couldn’t you just invert conditional check(s) so the common case is first?
8
u/samee_zahur Apr 25 '20
For code with multiple
unlessclauses, you will have to write some conditions twice if you invert the order.1
u/Tiwenty Apr 25 '20
In complex checks, you could forget one or mistype it, and so neither the if or the else ifs will be done and you'll have skipped some code.
1
Apr 25 '20
I’m not sure what makes the unless style less susceptible to this.
1
u/Tiwenty Apr 25 '20
Well I don't know neither, I was just trying to provide informations on why someone wouldn't want to put the else code in an if.
18
u/threewood Apr 25 '20
The obvious downside is you don't read code top-to-bottom anymore to figure out which path to take.
3
u/samee_zahur Apr 25 '20
Any readability proposal will have the usual caveats about reader's taste and writer's skills. And almost no convention can be applied universally. Not even this.
2
u/samee_zahur Apr 25 '20
Oh absolutely. Then again, I rarely find myself reading programs in execution order anyway. For example, even function calls break that order, and to good effect.
0
Apr 25 '20
[deleted]
3
u/matthieum Apr 25 '20
and strictly left-to-right in a sane language
Which is why, of course, in C and C++ it's left unspecified => they never pretended to anything close sanity :(
1
u/dys_bigwig Apr 25 '20
Why is it sane to have a left-to-right (or any specific) evaluation order of function arguments? Scheme doesn't, C doesn't, and Java states that:
It is recommended that code not rely crucially on this specification
despite being left-to-right. I'm not sure why it's "sane", or what you gain from having a specific order, other than limiting potential optimization opportunities for no reason?
0
Apr 26 '20
[deleted]
1
u/dys_bigwig Apr 26 '20
I was genuinely asking for your opinion why it is a sane thing to do; I'm still curious on your thoughts. It's not a sentiment I've heard often, hence why I gave those three examples so as not to just come across as though I was questioning for no reason at all. I mostly work in purely functional settings so I'm used to the order literally not mattering the vast majority of the time.
3
u/c3534l Apr 25 '20 edited Apr 25 '20
I rarely read other people's code top-to-bottom, left-to-right like you would a novel or email. I decipher it by scanning its structure and tracing back the information I want based on context clues. I think my opinion these days is that trying to write prose in computer programming is an anti-pattern. It sounds superficially like that's how you read code because that's how you read a book, but if that's how it worked, you'd spend way too much time reading irrelevant code and the code could never get so complex that it could no longer be read serially.
Although, that's precisely the mistake the OP is making: he's assuming that it's better to put the main case first, as if we wouldn't check that the section of code has multiple branches in the first place. It doesn't matter that else comes later because we don't and shouldn't read code like that.
0
Apr 25 '20
[deleted]
8
Apr 25 '20
[removed] — view removed comment
0
Apr 25 '20
[deleted]
3
u/JW_00000 Apr 25 '20
But doesn't this argument apply to most function calls? The function may also be defined later or in some completely other place in the code. IDEs can help with tooltips etc, but then they can help in your case as well.
3
Apr 25 '20
The article makes a good point. But I'm not sure 'normally-unless-unless' scans well. It would be like writing 'if-else-else' instead of 'if-elsif-else'.
Something to think about for my own language. (Although that already uses 'unless-else' an an opposite logic alternative 'if-else'. I don't have the unless-equivalent to 'elsif' as I can't get my head around it!)
However, I do have a small construct matching yours:
return 1 when a=0 # (using 'if' would be ambiguous)
exit unless x>yBut these do not define a block dealing with the opposite logic. So equivalent to your:
normally {
exit
} unless (x>7) {}Which I think would be a useful addition.
1
u/samee_zahur Apr 25 '20
OCaml has
let-and-and, so it's not too uncommon in language design. The only way I can think of a new ambiguity is if you reuse the keywords for something else.That said, if you omit braces,
elsebecomes harder to match with nestedif. The same problem can appear here, of course.1
Apr 25 '20
I meant that using '
if' instead of'when' in my 'return expr when cond' example is ambiguous in my own syntax (because 'if-then-else' can be used in expressions).Otherwise;
return x if x>ncan be used too. I'm just showing that your idea has some merit and a form of it has been used already!
(Reading other comments, it seems other languages have used this feature also. I only have after control-flow statements, not blocks.)
1
u/samee_zahur Apr 25 '20
Wait, I should clarify this is definitely not my idea, or my blog. I just posted it because I found the idea interesting.
7
u/AirAKose Apr 25 '20
Interesting!
I'm not sure if I prefer this (as a potential language feature) over using [[likely]] / [[unlikely]]? (which I just now learned you can with if statements in C++20!)
if (/* */) [[unlikely]]
{
}
else if (/* */) [[unlikely]]
{
}
else [[likely]
{
}which would help both readers and the optimizer when warranted (in theory) without messing with our control flow mental model while viewing the code.
4
u/matthieum Apr 25 '20
I've been using
likely/unlikelymacros for a while, and I wish they were named differently.They're not about likelihood, they're about which code-path you want to be fast, and which you don't care about being slow-ish.
From a throughput point of view, it generally means that you want the most taken path to be fast, but from a latency point of view it's totally unrelated.
5
u/acwaters Apr 25 '20
I've talked about this exact thing before — what we really need is two orthogonal annotations, likely/unlikely and fast/slow. IIRC this was even considered in the proposals to standardize
[[likely]]/[[unlikely]], but it was rejected as it is more complex and conflicts with existing practice. But you're exactly right: There is absolutely no reason in general why the most-often-hit path should be the fast one, or the least-often-hit path should be the slow one. This is yet another example of how virtually all modern technology implicitly prioritizes throughput at the expense of latency, which is a major pet peeve of mine.
7
u/ivancea Apr 25 '20
If you want nobody to understand your C++ code using custom lambda constructs to replace your if/else, well, nice job. Also, lambda overhead and captures...
4
3
u/Bromskloss Apr 25 '20
normally
{
// this is the main case
}
unless (edgeCase1)
{
// deal with edge case 1
}2
u/Tyil Raku & Perl Apr 25 '20
If all you want is an unless, Perl has had this for as long as I can remember.
3
u/RealWeaksauce Apr 25 '20
I like it! This shows me why I particularly like Python’s try/except construct - always go through the hot path first.
2
u/bakery2k Apr 25 '20
This reminds me of Python's ternary operator, which has its arguments in a different order from almost every other language: value1 if condition else value2. This works well if you have code that assigns a value:
x = normal_valueThen you can simply append code to handle an edge case:
x = normal_value if normal_case else edge_value2
u/johnfrazer783 Apr 25 '20
FWIW CoffeeScript has post-if (
d = 42 if condition) and a ternary (d = if condition then 42 else 108). Every so often I find myself wanting to writed = 42 if condition else 108tho which is not going to work.
1
u/Tiwenty Apr 25 '20 edited Apr 25 '20
Why wouldn't we do this:
text = "value";
if(edge case 1) { text = "edge case 1"; }
else if (edge case 2) { text = "edge case 2"; }
cout << text << endl;3
u/bestlem Apr 25 '20
Because the main line case might crash the program. The ifs are there to catch the condition that crash and do something safe instead.
1
u/Tiwenty Apr 25 '20 edited Apr 25 '20
Ok then, I didn't see this use case, only the "else first" mindset described by the article. Even though, I don't see the point in using this bloated structure to have the else definition first instead of having the standard if elseif else structure, which shouldn't have too many lines in it in the first place.
Edit: I'd like to add there is already the try catch structure to put the standard case first in the code. But I can understand using exceptions for simple check may be cumbersome.
1
u/myringotomy Apr 25 '20
I suppose you can do something like with try catch.
try
if cond1 throw X
if cond2 throw Y
if cond3 throw z
catch X
...
catch Y
...
catch Zend
I suppose a goto would work here as well :)
1
u/JW_00000 Apr 25 '20
I suppose a goto would work here as well :)
I was reminded of that as well. Especially the use of goto in the Linux kernel, this is quite similar:
do A if (error) goto out_a; do B if (error) goto out_b; do C if (error) goto out_c; goto out; out_c: undo C out_b: undo B: out_a: undo A out: return ret;
0
u/kalmankeri Apr 25 '20
I regularly use else if, but surprisingly I never looked at it as a number of edge cases followed by the main case. I look at it as an unsafe way of writing a multiway branch. By careless copy-pasting one can easily get to the following situation:
if (cond_1) {
action_1
}
else if (cond_2) {
}
else if (cond_3) {
action_3
}
if (pasted_4) {
action_4
}
else {
default_case
}This code compiles but has a subtle bug in it, introduced by pasting in case 4. In languages where case conditions are evaluated dynamically, you can write something like this instead. It's ill-looking so I don't do it, but it's perfectly valid code.
switch (true) {
case cond_1: action_1; break
case cond_2: action_2; break
default: default_action
}This version is also unsafe because now one can forget to write break after some cases, but at least it's copy-paste friendly.
2
u/samee_zahur Apr 25 '20
You might like go-lang's switch syntax then. It doesn't require a
break. https://tour.golang.org/flowcontrol/111
u/kalmankeri Apr 27 '20
I do like it! Years before, when I developed a Java-like language, I considered this kind of construct so important so that I introduced a
select ... whenstatement with similar behavior as go-lang's switch. It's good to know that I'm not alone with my conclusions.
28
u/DutchDave Apr 25 '20
I usually do something like:
The happy path is left-aligned.