Live data from Hacker News

Avoid Else, Return Early (2013)

blog.timoxley.com

331–340 of 601 posts

Re: Avoid Else, Return Early (2013)

#331
I find a compromise is best.

First, do the simple checks "Oh, this function returns an empty set if one of its parameters is null? Do that".

Then go into the main method body. In the main method body, I want to see elses on ifs. I'm okay with putting a return in each branch of the if/else, but what I find bad is when the main body is

```

  if(foo)
  {
     doLotsOfStufff();
     return myResult;
  }
  return bar;
```

That pattern I can't stand. That's as confusing as switch-block fallthrough.

For those cases, I prefer to see an else. If you must fall through to a final return while you've had a zillion other returns in your branching logic, then that deserves a comment at least explaining that this is the final fallthrough return.

Like

```

  if(foo)
  {
     doLotsOfStufff();
     if(somePositiveCase)
     {
        return myResult;
     }
     if (someOtherNeutralCase)
     {
        doSomePreparatoryThing();
        if (heyMoreChecks)
        {
           return positiveResult();
        }
     }
  }
  // this comment here is super important where we 
  // explain that we couldn't do any positive thing 
  // so this is a failure state.
  
  return barFail;
```

Re: Avoid Else, Return Early (2013)

#332

Earlier quoted context omitted.

Let's say we can see 30 lines on our screen and the average function takes 5 lines with OTBS. That means we can see 6 functions at once with OTBS and 5 with Allman. That makes a difference at least in my case.

Not being a pest here, but how often are you comparing more than 2 functions at a time? I can't say that I have ever dealt with code in over 20 years where I had to deal with more than 2 functions at once. Maybe I am mentally disabled, but I can only focus on one logical task at a time. Can other programmers multi-task their coding?

All the time, but to be honest, it's mainly side by side when I do. This is useful when building one function that acts on some other part of the code and I don't want to scroll / swap files back and forth.

I more meant it in the sense that it's nice to be able to soak in more of the code at once and avoid unnecessary scrolling.

Re: Avoid Else, Return Early (2013)

#333

Earlier quoted context omitted.

The One True Brace Style: https://softwareengineering.stackexchange.com/questions/9954... The name tells you that it won.

That link's favorite response actually refutes that brace style matters at all. No correlation with bug frequency detectable. So its all religion.

I wish this sentiment were expressed more often but also expressed less judgmentally and given more depth than sometimes occurs..

To say it is religion isn't to say "your preference is dumb". In my own code preferences I try to maintain a split between "have a reason I have confidence in" and "personal preference". And "easier to read" is almost always in the latter. (If you can say WHY, that is the actual reason, but your actual reason still has to be provable.)

Given the difficulty of finding good research and the inherent difficulty of the research (if familiarity is a big component to preference, and a proven ability to mentally parse code required to judge, then good luck running a control group) I have a lot of items I have confidence in being provable without having actual proof, but the lengthy preference list also means I'm willing to accept that each of those can switch columns.

Way too many of our "easier to read" defenses are really "it is easier to read because I'm familiar with it. I personally think camelCase is terrible - language has spaces for reasons! - but there is no denying that it is very common and that the vast majority of coders learned it first, an unfortunate self perpetuating cycle.

Nonetheless, shown research that said I was wrong (assuming said research had taken familiarity into account) I would change my stance rather than dig in my heels...even if that change were to only add "but that's just me" to the end of it.

Re: Avoid Else, Return Early (2013)

#334
This is one of the reasons why I grew to really love function overloading, especially in combination with pattern matching (I learned both first with Clojure, perhaps, but have only become comfortable with them now with Elixir). I can often avoid if/then statements altogether! It's also interesting how error handling becomes much less of an issue.

I do a lot of javascript programming, and it's often quite frustrating to not have these and other features available. While I by no means hate Javascript, I have to admit I feel a bit silly about being defensive about it in the past. I just didn't know what I was missing, or didn't see what the big deal was.

Re: Avoid Else, Return Early (2013)

#335
post #6

A more formal name for this approach is / could be Guard Clauses: https://refactoring.com/catalog/replaceNestedConditionalWith... . This pattern has been elevated to a language construct in Swift: https://thatthinginswift.com/guard-statement-swift/

As usual I found myself writing these more and more before finding out there was a word for them.

Are there any preprocessors or libraries to make statements like this easier in Javascript? Sometimes the guard statements can be longer than the function code and I go back and forth on whether to throw (forces the caller to anticipate) or return (causes lots of silent failures).

It would be great to use a defined approach.

Re: Avoid Else, Return Early (2013)

#336
post #166

Earlier quoted context omitted.

That's fine -- the Python folks have their own share of religious wars (starting with: tabs, or spaces?) :-)

Tabs, everyone can configure them however they want. :-)

Until you need spacing that isn’t a multiple of your tab width then you’re screwed.

Re: Avoid Else, Return Early (2013)

#337
post #334

This is one of the reasons why I grew to really love function overloading, especially in combination with pattern matching (I learned both first with Clojure, perhaps, but have only become comfortable with them now with Elixir). I can often avoid if/then statements altogether! It's also interesting how error handling becomes much less of an issue. I do a lot of javascript programming, and it's often quite frustrating…

You can approximate method overriding in JavaScript by overriding the prototype method value and calling .apply on the original from inside the new one.

Re: Avoid Else, Return Early (2013)

#338

Earlier quoted context omitted.

I have doubts about whether "real" projects generally have these kinds of concerns. But even if they do, you can clean them up in a `finally`, or your language's equivalent.

Most languages with try/catch/finally don't have checked exceptions, so handling resource management in the those schemes is really brittle.

`finally`/RAII doesn’t depend on checked exceptions. It always runs (short of something that aborts the program without unwinding the call stack; and in those cases single-exit won’t save you).

Re: Avoid Else, Return Early (2013)

#339
really not a fan of "return early" style, because of logging: I like to have the ability of look at the business logic flow as/if needed and monitor its states but multiple returns per method force having complex "ifs" logged one after another, while in a single return pattern you can concatenate the reasoning into a single log line.

Having a single log line is extremely useful in general as you don't have to filter all the relevant information within other log lines and makes easier to extract a single thread pathway within a multi-threaded application.

however I do like this snippet: > Try keep the “meat” of your method at the lowest indentation level.

but I prefer doing that isolating atomic logics within their own method, instead of having multi-step pathway with early returns

Re: Avoid Else, Return Early (2013)

#340

Earlier quoted context omitted.

I'm with you on Allman style braces, prefer it and find them much easier to read. As everyone else seems to use K&R I've just had a adapt over time :-(

What's interesting to me is, anecdotally, the people I know who are the biggest K&R haters are people who started with K&R, then had to switch to Allman for a significant length of time, and then had to switch back to K&R.

That probably tells you more about the haters than the brace style. That was my career path, and while I've gotten used to reading Allman braces, I've heavily relied on tooling (especially Visual Studio) to auto-format my K&R (or 1TBS) braces for whatever project I'm in. Same thing with tabs/spaces.

There are lots of sane ways to read code, but consistency is key. It's hard to change muscle memory in how I type, though, so I think auto format is the way to go.

Post reply on HN