News for hackers. Stuff that matters.
Re:Early exit is a tail call optimization of procedural lang... by jpollock on Monday December 14, 2015 @12:53PM (#10732537)
I've been in the "only a single return" and "early return plz" camps at various points in my career.

Right now? I'm early return.

When I wrote C and C++ code with locks and malloc/free? One exit only.

It's all about avoiding bugs.

In C code heavy with locks and memory allocation, you need to make sure your post-conditions are correct. That is near impossible when there is more than one return [1].

In C++, with RAII and Java with "try-with-resources", I can ensure proper cleanup. At that point, it's about making it easy for someone who is reading the code to avoid screwing it up. I need to make it easy for them to flow through the code, keeping the cognitive load as low as possible. Functions do what they say on the box and _only_ what they say on the box. At that point, my goal is to make a decision, act on it and move on. I don't want to carry that state forward - it means I have to keep it in mind for every line after it. I'm even trending towards having the majority of the methods in my classes be static functions with no state.

Finally, if I've got a function that has two different flows and I'm deciding between them with an if? I've probably actually got two different functions pretending to be one. I then try to refactor and get rid of the if.

[1] http://programmers.stackexchange.com/questions/154974/is-thi...

Re:Early exit is a tail call optimization of procedural lang... by legulere on Monday December 14, 2015 @02:08PM (#10733076)
But in C you usually use `goto Error;` which basically is just a `return` + you can do the cleanup yourself.
Re:Early exit is a tail call optimization of procedural lang... by CyberDildonics on Monday December 14, 2015 @05:02PM (#10734283)
That means that you have to put all your unlocks and deallocations there AND you have to check them to see if they were allocated/locked in the first place.
Re:Early exit is a tail call optimization of procedural lang... by Stratoscope on Monday December 14, 2015 @01:09PM (#10732663)
The error checking example conflates two different things:

• Early returns vs. single return.

• Excessive nesting vs. simpler flatter if/else.

The real problem with the "before" example is the excessive nesting. I do prefer early returns myself, but even if you wanted to use the single-return style, you could simply un-nest the whole thing:

    public string Execute( int integer, string str, bool boolean ) {
        string result;
     
        if( integer <= 42 ) {
            result = "Error: Integer is too small";
        } else if( string.IsNullOrWhiteSpace(str) ) {
            result = "Error: String is null or empty";
        } else if( ! boolean ) {
            result = "Error: Incorrect boolean";
        } else {
            result = "Success";
        }
     
        return result;
    }
It's a bit ironic that this is C# code, because ReSharper would offer to un-nest the code for you.

Also, this really has nothing to do with tail call optimization.

Re:Early exit is a tail call optimization of procedural lang... by barrkel on Monday December 14, 2015 @03:35PM (#10733628)
Frequently the checking is dependent on passing the previous clause. Something like:

    if (x == null)
        return "x is required";
    if (x.length < 3)
        return "too few elements in x";
    if (x[0] == null)
        return "first element missing";
The point here being that each successive check is testing something that is only valid if the previous check passed. This can't be so easily converted to your if/else pattern without re-encoding the early exit in the form of a complex boolean (&& and || have early exit built in).

The concept's applicability to tail call optimization is only by analogy with the mental stack; just as tail call optimization sets up the call such that the current stack frame no longer exists, early exit sets you up to remainder the rest of the code without regard to any potential alternate code paths (i.e. a potential else branch on an early if statement) later; the mental frame of a long if statement no longer exists. The analogy is a little bit stretched; of course it is not a technical isomorphism, but nobody ever said it was.

Re:Early exit is a tail call optimization of procedural lang... by Stratoscope on Monday December 14, 2015 @04:09PM (#10733884)
As I mentioned, I prefer early returns as well, and I wasn't recommending the if/else structure as an alternative to early returns.

My only point in showing that code was to illustrate what I see as the bigger problem in the example: the use of nested if and else statements when non-nested ones could be used instead. Personally I would get rid of the nesting by using early returns, but for someone who objects to that for any reason, the non-nested if/else chain is a nice alternative.

Also, the series of returns you show here could easily be written as a chain of if/else for those who prefer that style. I'm not sure why you said it requires a complex boolean expression; this code is equivalent to the series of returns:

    string result;
    if( x == null ) {
        result = "x is required";
    } else if( x.length < 3 ) {
        result = "too few elements in x";
    } else if( x[0] == null ) {
        result = "first element missing";
    } else {
        result = "the real result";
    }
    return result;
Again, I don't particularly like this style, although it is better than the deeply nested if/else. I prefer the series of returns that you listed in your comment.
Re:Early exit is a tail call optimization of procedural lang... by tikhonj on Monday December 14, 2015 @01:42PM (#10732896)
Return statements and "early exit" are not built into functional languages. If the language, like Scheme, supports continuations, we can use callCC to implement an early return[1]:

    (define (example x)
      (call/cc (lambda (return)
        (when (< x 0) (return #f))
        ; more code, including possible more calls to return
        0)))
However, most functional languages do not have callCC built in. Happily we can get a similar effect by writing our code in continuation-passing style (CPS)[2]. (Think Node.js.)

Nominally, CPS has some overhead because of the extra function calls involved. However, a CPS transform also puts every call in tail position, making them eligible for tail call elimination. This means that we can use CPS with no function call overhead in a language with proper tail calls.

What does this mean in practice? It means that calling a callback in CPS style—which, being in tail position, can be eliminated—is effectively just a jump under the hood. Not too different from return!

Putting it all together, we get that tail call elimination lets us write code in continuation passing style with no extra over head which gives us access to continuations that we can use to implement an early return in languages without return.

This turns out to not be what the article was on about, but I think it's more interesting.

[1]: Code from a StackOverflow answer by Nathan Shively-Sanders which goes into more detail: http://stackoverflow.com/questions/2434294/scheme-early-shor...

[2]: I wrote a brief explanation of CPS on Quora: https://www.quora.com/What-is-continuation-passing-style-in-...

Re:Early exit is a tail call optimization of procedural lang... by ridiculous_fish on Monday December 14, 2015 @03:22PM (#10733537)
Is it possible to use CPS with functional primitives like map? Or do you have to implement CPS-savvy replacements? It doesn't seem like a CPS transform would let you early-exit from map in tail position.
Re:Early exit is a tail call optimization of procedural lang... by tikhonj on Monday December 14, 2015 @03:42PM (#10733689)
Right, you'd need a CPS version of map. Luckily map isn't really a "primitive", it's just a library function, so using a different version of map is not a big deal.

One way to think about it is that languages with callCC built in are just transformed to CPS by the compiler before being run, which includes transforming the definition of map. (In fact, this is a reasonable strategy for compiling Scheme, I believe.)

It's pretty easy in Haskell which wraps CPS into a monad (Cont) because you use mapM from the Control.Monad library instead of having to write a specifically CPSed version of the function.

Re:Early exit is a tail call optimization of procedural lang... by fantasticsid on Monday December 14, 2015 @12:13PM (#10732294)
I would rather see more articles like this on hacker news!
Re:Early exit is a tail call optimization of procedural lang... by dang on Monday December 14, 2015 @02:25PM (#10733156)
Anyone who wants to share their preference with us is welcome to email [email protected]. We're interested.
Re:Early exit is a tail call optimization of procedural lang... by DanBC on Monday December 14, 2015 @02:54PM (#10733338)
How often do you visit /newest to upvote the content you want to see?
Re:Early exit is a tail call optimization of procedural lang... by acchow on Monday December 14, 2015 @01:53PM (#10732987)
Was like this a few years ago.
Re:Early exit is a tail call optimization of procedural lang... by jkot on Monday December 14, 2015 @12:21PM (#10732357)
Original code seems like really bad way to check validity of parameters. Is this type of programming common in some languages? I have never seen similar code in Java.
Re:Early exit is a tail call optimization of procedural lang... by jpollock on Monday December 14, 2015 @12:36PM (#10732461)
Some groups have a "Functions can only have a single entry and single exit point" rule, meaning you have to jump through a lot of hoops.

Sometimes it is required. In Java, before try-with-resources, if you had any resource management (locks, file descriptors, sockets), a single exit point made resource management simpler. C code tended to have similar rules (or GOTO's to jump to the exit block in the function). C++ just used RAII, and made it the destructor's problem.

Re:Early exit is a tail call optimization of procedural lang... by SideburnsOfDoom on Monday December 14, 2015 @01:02PM (#10732606)
Right - that single-exit-point rule is generally a holdover from C.

It is pointless in languages like C# or Java which have GC and 'try' or 'using' blocks. In some cases the single return is nicer, but this is not universal nor is single return "required" in all cases.

In functional languages such as F#, Haskell or Erlang where the method is usually side-effect free and uses pattern-matching, multiple return-points are completely normal and no-one even sees an issue.

Re:Early exit is a tail call optimization of procedural lang... by jdmichal on Monday December 14, 2015 @03:25PM (#10733555)
Java has always allowed try-finally blocks, which is what a try-with-resources compiles down to anyway.

    Resource resource = new Resource();
    try {
        if (a)
            throw new Exception("Oops!");
        else if (b)
            return resource.doBStuff();
        else
            return resource.doStuff();

    } finally {
        resource.close();
    }
Re:Early exit is a tail call optimization of procedural lang... by bjacks on Monday December 14, 2015 @05:21PM (#10734427)
I think that if the author re-wrote the first method in a cleaner way, composed of lots of smaller methods with descriptive names then the code would be a lot more readable, and you wouldn't even need to debate the whole multiple returns versus single point of return thing because your "mental stack" could handle either option equally well.

For example:

  public string Execute(int integer, string str, bool boolean) {
    string result;

    if (isValidInteger) {
       result = validateStringAndBool(str, boolean);
    } else {
       result = “Error: Integer is too small”;
    }
   return result;
}

  private string validateStringAndBool(string str, bool boolean) {
     if (!string.IsNullOrWhiteSpace(str)) {
       return isValidBoolean(boolean)          
     } else {
        return  “Error: String is null or empty”;
     }
  }
 
  private string isValidBoolean(bool boolean) {
     if (boolean) {
        return “Success”;
     } else {
        return “Error: Incorrect Boolean”;
     }
  }
And yeah, I can't see how this has anything to do with tail call optimization other than a fluffy analogy to stacks - mental and programmatic.
Re:Early exit is a tail call optimization of procedural lang... by hellofunk on Monday December 14, 2015 @09:26AM (#10731113)
Would be nice to see more serious study of this for a language like C++. It would take either TCO or Garbage Collection to make reliable, robust persistent data structures a possibility in C++, and more would prefer TCO of these two. That would open a big door into more powerful functional programming idioms for C++ than currently exist, even with the latest language standards.
Re:Early exit is a tail call optimization of procedural lang... by adrianm on Monday December 14, 2015 @09:51AM (#10731255)
How would TCO help? I've never read anything about the connection between TCO and persistent data structures. GC on the other hand is a known, and often assumed, requirement in the literature. Sounds interesting!
Re:Early exit is a tail call optimization of procedural lang... by jacquesm on Monday December 14, 2015 @10:38AM (#10731560)
TCO can be done more readily if you know for a fact that all the parameters passed into the function were not modified during the execution of the function.
Re:Early exit is a tail call optimization of procedural lang... by GFK_of_xmaspast on Monday December 14, 2015 @01:16PM (#10732704)
More reasons to be aggressive about marking things const.
Re:Early exit is a tail call optimization of procedural lang... by hellofunk on Monday December 14, 2015 @03:52PM (#10733754)
consider this interesting discussion:

https://github.com/BartoszMilewski/Okasaki/issues/1#issuecom...

his blog has more details

Re:Early exit is a tail call optimization of procedural lang... by pjc50 on Monday December 14, 2015 @10:43AM (#10731606)
Compilers already implement some TCO. What specifically do you mean about "reliable, robust persistent data structures" that you think is currently not possible in C++?
Re:Early exit is a tail call optimization of procedural lang... by hellofunk on Monday December 14, 2015 @03:51PM (#10733749)
See here:

https://github.com/BartoszMilewski/Okasaki/issues/1#issuecom...

This guy knows what he is talking about. His blog has a lot of interesting discussion in this area.

Re:Early exit is a tail call optimization of procedural lang... by glastra on Monday December 14, 2015 @10:21AM (#10731460)
To me, this only makes sense if you always read source code sequentially. Humans are not machines, and most often you will not be reading code (especially code with branches) in a top-bottom manner.

Having multiple return statements in a method actually renders the method LESS readable. I understand the first proposal is also usually implemented with many return statements, but they could be replaced with a variable assignment, variable that is then returned at the end of the method (as in the example). If that variable is final (or whatever the C# equivalent is), that's even better.

Re:Early exit is a tail call optimization of procedural lang... by Bognar on Monday December 14, 2015 @10:58AM (#10731728)
> Having multiple return statements in a method actually renders the method LESS readable.

I 100% disagree. Introducing a variable instead of using multiple returns means I now have to keep track of yet another variable throughout the entire rest of the method. Is it modified before it's returned? Gotta read the whole thing to find out.

Early returns reduce the complexity of a method by reducing the number of possible states as you move through the method.

Re:Early exit is a tail call optimization of procedural lang... by glastra on Monday December 14, 2015 @11:47AM (#10732102)
> Early returns reduce the complexity of a method by reducing the number of possible states as you move through the method.

As I said in other comments, early returns for exceptions and bad input are fine. They are exceptions, though, not return statements. Go ahead and use return if you want/can, although I wouldn't.

If it's not for an exception or input validation failure, then we have something like:

"Alright, so here we do this, unless this, that and that other condition over there were true earlier, because the method would've returned then..."

I find that the complexity to keep track of with this approach is pretty much the same, or even more depending on the branching.

Re:Early exit is a tail call optimization of procedural lang... by adamc on Monday December 14, 2015 @10:38AM (#10731563)
I don't think I fully understand your comment. Regardless of whether I've read the whole program top-down, it is definitely easier for me to understand early-exit logic in a routine than to keep the mental stack of conditionals going, particularly when (as is often the case) the early exits consist of various deviations from the "main sequence" code (e.g., validations failing or other edge-cases).
Re:Early exit is a tail call optimization of procedural lang... by AlisdairO on Monday December 14, 2015 @11:09AM (#10731811)
Completely agreed.

I think early returns deep in the logic of a method can be problematic, but I think early returns at the top of a method before you get to the meat of the logic are very readable.

Re:Early exit is a tail call optimization of procedural lang... by glastra on Monday December 14, 2015 @10:54AM (#10731693)
I was speaking from a general point of view. I find early exit on validation failure acceptable, although it'd make more sense to use exceptions and not a simple return.

A sufficiently complex method with 5 return statements all scattered in between to treat real cases (i.e. not failures or conditions that should raise an exception) is certainly less readable than the same functionality refactored to a single return statement at the end with the proper use of branching.

Aside from readability, it also increases maintainability. What if you have to introduce a modification to your logic that applies a transformation to the result? Should you modify it in 5 places, or 1?

Re:Early exit is a tail call optimization of procedural lang... by SideburnsOfDoom on Monday December 14, 2015 @11:26AM (#10731927)
> A sufficiently complex method with 5 return statements ... is certainly less readable than the ... single return statement at the end version

In all cases? How can you even measure that? How can you do it in a way that's free of bias?

If you've never used a style, of course you will find it harder. Dogmatic assertions that boil down to "what I'm used to is objectively better because of how it feels to me" are IMHO harmful.

Re:Early exit is a tail call optimization of procedural lang... by glastra on Monday December 14, 2015 @11:37AM (#10732016)
I cannot measure that on anyone else other than myself. This is a place to express opinion.

I've read (and sadly written) enough code in both styles to know what _I_ (and all the peers I've bothered to ask with concrete examples, for that matter) find easier to understand, but there's of course all kinds of bias in there as well.

Taking comments in HN as fact or truth is harmful, and (replying to your other comment) waving acronyms around is equally harmful, if not more. You can't possibly assert that writing code in one or another way is easier or harder, or that the code is "more complicated" (precisely what we don't seem to agree on). To be honest, I find it easier to write methods with single return statements (and exceptions to handle... well, exceptions[^1]). It all seems clearer in a "stream of thought" kind of way. Engrish is hard, sorry.

[^1]: Early returns are exceptions for lazy coders.

Re:Early exit is a tail call optimization of procedural lang... by SideburnsOfDoom on Monday December 14, 2015 @11:45AM (#10732080)
> You can't possibly assert that writing code in one or another way is easier or harder

In general, of course not. I think that both single-return and multiple-return styles can be valid and readable. But of course both can be obfuscated.

But give me a particular piece of logic and I might give an opinion on which style I would use for it.

& if you think YAGNI is harmful, you should see the pointless code from people who have never thought that way!

Re:Early exit is a tail call optimization of procedural lang... by conceit on Monday December 14, 2015 @05:02PM (#10734280)
the term callback hell comes to mind, although I'm not sure that's the entire problem you quoted
Re:Early exit is a tail call optimization of procedural lang... by SideburnsOfDoom on Tuesday December 15, 2015 @04:13AM (#10736708)
I wasn't talking about callback hell (1) but if you want to do so - the point is that if the "nested callbacks" style is objectively worse (and this seems likely) then this can actually be measured.

Lines of code and cyclomatic complexity (2) is just the start.

You would have to do something like ... e.g. take a group people skilled in some other programming language, give them a basic grounding in Javascript, and have them work with some JS code samples with and without nested callbacks.

If there is clear difference in code comprehension, time to modify the code, lines of new code to accomplish a goal, and resulting bug count then you can have an informed opinion on if this code style is really objectively so bad.

That seems like a costly and time-consuming procedure. But if some academic institution did this I'd be pleased - some scarce data and some actual science is IMHO is worth a thousand opinions in this kind of recurring stylistic debate.

1) http://callbackhell.com/

2) https://en.wikipedia.org/wiki/Cyclomatic_complexity

Re:Early exit is a tail call optimization of procedural lang... by SideburnsOfDoom on Monday December 14, 2015 @11:01AM (#10731744)
> What if you have to introduce a modification to your logic that applies a transformation to the result? Should you modify it in 5 places, or 1?

In 1 place, clearly. The multiple-return version would require a bit more refactoring at this point, either extracting another method or introducing the "return value" state var at that point.

Why not code it with single return up front? Simple: most likely, You Aren't Going To Need It. The YAGNI principle says to make the code more complicated when you need to, not before.

Re:Early exit is a tail call optimization of procedural lang... by phamilton on Monday December 14, 2015 @11:04AM (#10731769)
"Oh... We call function foo. Let's go see what function foo returns. (Scroll to the end of the function)"

With a single return, I can at least follow that thread fairly easily and sometimes it's just a few lines back in a large function. With many returns, I'm forced to start at the beginning of the function.

There a dozen or so other culprits that make this difficult. Assignment in a block can be just as bad, for example, since I can't know which assignment occured without looking at all of them.

Re:Early exit is a tail call optimization of procedural lang... by Vaskivo on Monday December 14, 2015 @11:23AM (#10731900)
I disagree.

The function signature should be explicit about what it does and returns. If it has a static/defined return type I know what I can expect from it. The function name should also be explicit about what it does and returns.

Scrolling down to the end just to see a 'return books' statement is usually useless.

If I need to read the whole function, I'd rather have early exits instead of nested ifs. It's easier to read because it follows the logic of "if (such and such condition): nothing else to do -> return;"

Re:Early exit is a tail call optimization of procedural lang... by SideburnsOfDoom on Monday December 14, 2015 @11:32AM (#10731977)
> sometimes it's just a few lines back in a large function

Large functions that have both side effects and return values are themself the readability problem.

Early return is not, it is a succinct way to express some functions with return values.

Re:Early exit is a tail call optimization of procedural lang... by camgunz on Monday December 14, 2015 @05:37PM (#10734544)
I like this ergonomics argument, particularly from a reader's perspective. But having had to read some single return value code recently, I found that the return value returned at the end of the function was rather unhelpful; it usually boiled down to "return rv;". I then had to go back up to the top of the function and follow through the nest of passed conditionals and side effects, fall throughs, and failed conditionals to see how "rv" was modified throughout the function. The non-linearity cost me a lot more thought, whereas with multiple return value code the failed conditionals are "tossed" out of my head very quickly. I think, given that you almost always end up reading the whole function anyway (which is probably good), linear is better than non-linear and consistency (bail early) is better than inconsistency (anything goes) when it comes to error handling.
Re:Early exit is a tail call optimization of procedural lang... by phamilton on Friday December 18, 2015 @03:21AM (#10757354)
I come from an FP background, and so I tend to avoid multiple assignment as well. In such a scenario, there's a single line that assigns rv. Each of the variables used in assigning rv are each assigned just once. I can follow the graph fairly easily until I get to the bit I need. Often its something like "what conversion rate for currency are we using?" and following that chain gets me there quickly.
Re:Early exit is a tail call optimization of procedural lang... by camgunz on Sunday December 20, 2015 @12:33AM (#10766176)
Yeah, I can definitely see how if you're disciplined it can be effective. But in my case, I've seen integer return values hold status codes from multiple modules and libraries, file handles, and enum values all in the same function just to twist everything together so that no matter where it stops executing, "rv" has some kind of value so that the ending "return rv" won't just return success. It was total madness, and it's really hard to do anything as complicated and fragile as that with early returns.

I will admit though that no programming style will sufficiently protect against bad coding :). I'm sure even if this person did everything I advised, they'd still find a way to overcomplicate and confuse things. So maybe the issue is moot, or at least bigger than style.

Re:Early exit is a tail call optimization of procedural lang... by glastra on Monday December 14, 2015 @11:09AM (#10731806)
Exactly. See single return statement, highlight variable, see branch structure at a glance, ???, profit.
Re:Early exit is a tail call optimization of procedural lang... by cballard on Monday December 14, 2015 @11:26AM (#10731924)
Swift solves this with "guard" statements, which must return if their condition fails. This is most commonly used in combination with converting optional values to non-optional values, to prevent pyramids of doom.

    guard let something = maybeSomething else { return ... }
Re:Early exit is a tail call optimization of procedural lang... by SideburnsOfDoom on Monday December 14, 2015 @10:48AM (#10731638)
> Having multiple return statements in a method actually renders the method LESS readable

Does it? I don't find it that. However, if you have never read code of this style before, it will be unfamiliar to you and you will find it less readable. But you can overcome this with practice.

I would rather say that it depends - both are valid styles, sometimes it's more readable to use multiple return statements and sometime less. As a programmer you know both and pick the option that is better suited to the problem at hand.

Re:Early exit is a tail call optimization of procedural lang... by btilly on Monday December 14, 2015 @03:34PM (#10733620)
I have seen this claimed many times, and I've never seen any research for it that in the end came down to more than personal prejudice.

On the other hand http://www-cs.stanford.edu/people/eroberts/papers/SIGCSE-199... offers concrete reasons why early returns make sense.

Re:Early exit is a tail call optimization of procedural lang... by legulere on Monday December 14, 2015 @02:06PM (#10733062)
This would be pretty awesome to have as a lint in static code analysis tools.
Re:Early exit is a tail call optimization of procedural lang... by askafriend on Monday December 14, 2015 @02:01PM (#10733031)
For startups too