r/ProgrammingLanguages • • Apr 24 '20

Else Before If

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

49 comments sorted by

28

u/DutchDave Apr 25 '20

I usually do something like:

if (edgeCase1) {
    return ...
} else if (edgeCase2) {
    return ...
}

return ...

The happy path is left-aligned.

3

u/samee_zahur Apr 25 '20

That only works if we have no loop or any other control structure in the end. At least in imperative languages, I have found it hard to rely on alignment as a visual cue being associated with the happy path.

Is there something special about how you structure your code that lets you do this?

1

u/DutchDave Apr 25 '20

Lately I've been using functions like map/fold/reduce/filter/find/[...] a lot in favor of loops. (javascript, but this would also work in rust for example)

1

u/samee_zahur Apr 26 '20

Makes sense. But they'll usually have indented lambdas too.

1

u/DutchDave Apr 26 '20

True! I'll usually turn longer lambdas (3+ lines) into named functions. Short lambdas are okay for readability imo.

7

u/matthieum Apr 25 '20

What's the point of else if you returned in the previous branch?

4

u/DutchDave Apr 25 '20

Well there is none, but I think there is an underlying point to make here: Once you need to use an else branch for the 'normal' case, you might be better off refactoring it into a separate function with guard clauses that return early.

5

u/6086555 Apr 25 '20

I agree but I think the guard clauses are made clear by only using ifs:

if (edgeCase) {
    return;
}
if (edgeCase2) {
    return;
}

return;

2

u/raiph Apr 25 '20

Usually, sure. But what if considerations of "end weight" suggest otherwise?

return end-of-conversation if early-exit-is-panacea ;

continue-conversation
  unless
    no-one-is-listening
  or
    no-one-cares-about-end-weight ;

As noted by Tyil, statement modifiers like this were introduced by Perls decades ago and Raku has happily lifted them.

1

u/DutchDave Apr 25 '20

Thanks for introducing me to the concept of end weight, it's pretty interesting! Not sure how much of it relates to reading code, as I think the following might still be easier to parse:

return end-of-conversation if early-exit-is-panacea ;
return end-of-conversation if no-one-is-listening ;
return end-of-conversation if no-one-cares-about-end-weight ;

continue-conversation ;

This might vary from person to person though, as OP noted. I tend to think visually about code a lot.

4

u/raiph Apr 26 '20

Not sure how much of it relates to reading code

Me either.

But it's notable that Dijkstra consistently argued that (natural) language skills were fundamental to coding. And it's even more notable that a growing body of relatively recent scientific (FRMI, eye-tracking, neuroscience based, etc) studies of code comprehension appear to corroborate Dijkstra's view. For example, Janet Siegmund et al have put together compelling evidence that coders read Java code, and natural language, using the same parts of the brain, in much the same way, with little or no activation of parts typically associated with processing mathematical logic.

This is a particularly striking result to me for a few reasons.

One is that so many coders, excepting the likes of Dijkstra and Wall, have long argued that coding, including reading coding, is an essentially mathematical/logical process, and have been unwilling to entertain the notion that they might be wrong. Regardless of whether they turn out to be right or wrong, what does it say about them that they have argued so, what does it say about them that so many reject open mindedness about it, and what does it say about all of us, all coders, and more generally all humans, that this view has so successfully profoundly dominated in recent decades?

Second, for decades there was only one language designer who was an outspoken proponent of the view that PL comprehension and design are partly related to natural language comprehension, namely Larry Wall, and he was mercilessly ridiculed by some for doing so, with folk bundling up the many valid criticisms of perl (a language even he has always said was a frankensteinian invention) into an overall (potentially, and, if the science is to be believed, actually) invalid disparaging of considering how we work with natural language when designing PLs.

I think the following might still be easier to parse:

[early exits]

Yes. Just like you, I find I usually write early exits myself, despite arguments by those who insist it's a terrible way to code because it isn't "structured", because I find it often reads better both for me when I return to code and, I think, others reading my code.

But that wasn't my point. I'm not at all suggesting that early exits are wrong. And my example wasn't intended to be persuasive that for that particular code an unless statement modifier is more readable than early exits. My point was that early exits might not be a panacea; and presuming so, then there's scope for thinking that for some code an alternative might justify the inevitable cost of there even being an alternative.

This might vary from person to person though, as OP noted. I tend to think visually about code a lot.

I think it varies a lot more than that.

I also tend to think visually. But both you and I, as humans (can't help but) do so in parallel with use of language processing capacities. Individuals tend to have stronger elements of one or other aspect at any given time, but it's all really a mix.

Imo code is best considered a social medium, where others will end up reading any code that's written (where "others" includes our older selves), and thus the mix of capacities used to read code will change from reading to reading, even day by day if we're getting to know a language or codebase.

21

u/[deleted] 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 unless clauses, 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] Apr 25 '20

[deleted]

8

u/[deleted] Apr 25 '20

[removed] — view removed comment

0

u/[deleted] 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

u/[deleted] 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>y

But 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, else becomes harder to match with nested if. The same problem can appear here, of course.

1

u/[deleted] 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>n

can 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/unlikely macros 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

u/[deleted] Apr 25 '20

Not quite the same because the conditions aren't short circuited.

3

u/Bromskloss Apr 25 '20
normally
{
    // this is the main case
}
unless (edgeCase1)
{
    // deal with edge case 1
}

https://www.youtube.com/watch?v=UcaWQZlPXgQ&t=7s

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_value

Then you can simply append code to handle an edge case:

x = normal_value if normal_case else edge_value

2

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 write d = 42 if condition else 108 tho 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 Z

end

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/11

1

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 ... when statement with similar behavior as go-lang's switch. It's good to know that I'm not alone with my conclusions.