Live data from Hacker News

Avoid Else, Return Early (2013)

blog.timoxley.com

561–570 of 601 posts

Re: Avoid Else, Return Early (2013)

#561

Programmers with lots of hours of maintaining code eventually evolve to return early, sorting exit conditions at top and meat of the methods at the bottom. Same way you evolve out of one liners. Same way comments are extra weight that should only be in public or algorithm/need to know areas. Same way braces go on the end of the method/class name to reduce LOC. Same way you move on from heavy OO to dicts/lists. Same w…

> Same way you move on from single condition bracket-less ifs. This is one of those things that whether you drop it or not, you recognize the times it's caused you severe pain because you didn't notice it was single line when adding a statement, such as a debugging one, and all of a sudden the conditional part isn't what you were expecting. This is actually one of the things I love about Perl. Single line conditional…

This can be horrible in JavaScript. It can make code really ugly. I have had to deal with code that looks like this recently:

    if (condition){
        doSomething()
        doSomethingElse()
    }
    else
       doSomethingDifferent()
    doSomethingConfusing()  // is this part of the else or not??

Perl got many things right. Its a shame it seems to have fallen away as a language.

Re: Avoid Else, Return Early (2013)

#562
post #560

Earlier quoted context omitted.

> Fewer LOC means more code on the screen, which means you can more easily grasp the functionality of some piece of code, uh ? for me the less code on each line and the easier it is to read

That depends. Python's pep guidelines has an 80 char wide rule, but I personally find that a lot harder to read than one long line (most of the time).

I find the 80 chars too short but, and this is highly objective, I notice I am more relaxed and usually having more fun when working with shorter lines. The best theory a I have as to why is just that most lines in code are short so long lines require making my eyes deviate from the code structure. If there is a long line, it will probably be out of place. So, my personal rule is to avoid that one or two lines that juts out beyond the lines above and below it. If all lines in a block are long, they are often similar commands/expressions which makes them orderly, and not so discomforting.

Re: Avoid Else, Return Early (2013)

#564

Earlier quoted context omitted.

Logical AND in JavaScript can be used as a guard, by why in the world would you think of it as anything other than a logical AND? If you start thinking it is a "guard operator", I would think that going down the wrong path, which might promote misunderstanding of the behavior.

> which might promote misunderstanding of the behavior This isn't a misunderstanding, binary logical operators in JS short-circuit like this by design. I believe && and || returned a boolean value in the past, but were explicitly changed to support this behaviour.

Quoting ECMA-262 First Edition (June 1997), Chapter 11, Section 11 (Binary logical operators)[1]:

    The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
    
    1. Evaluate LogicalANDExpression. 
    2. Call GetValue(Result(1)).
    3. Call ToBoolean(Result(2)).
    4. If Result(3) is false, return Result(2).
    5. Evaluate BitwiseORExpression.
    6. Call GetValue((Result(5)).
    7. Return Result(6).
That is, the behavior has always been "If the first expression is false-ish, return the first expression, otherwise return the second expression" ("BitwiseORExpression" is a class of expressions that include a lot of things, including equality operators).

JavaScript does not have any operators that is not explicitly listed in a version of ECMA-262. It would be correct to refer to the construct as a "guard", but incorrect to refer to it as a "guard operator". Calling it "guard operator" also does not promote an understanding of the underlying construct.

1: https://www.ecma-international.org/publications/files/ECMA-S...

Re: Avoid Else, Return Early (2013)

#565
post #426

Earlier quoted context omitted.

Do they? All the Python folks I've ever seen express an opinion on style have said "follow PEP 8". Unsurprisingly, PEP 8 does have a rule for tabs vs. spaces: https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces (spaces, of course)

I love Python but as a long time C programmer I can't understand the preference for spaces in PEP 8. Tabs are semantic and only take one key press for movement back and forth and to delete. If you see 1 tab you know it meant one indentation level. With spaces you have to think. Plus with spaces you are stuck with 2/4/8 spacing(unless you reformat), with tabs you can configure your editor to your preferences.

> with tabs you can configure your editor to your preferences

Except that you can't because people using tabs will invariably start mixing tabs and spaces because they can't separate indentation from layout. So the code will be messed up unless you configure your editor to someone else's preferences. Also, I'm sure there is some obscure git setting to de-uglify tab users' diffs, but I'd rather not find out.

Re: Avoid Else, Return Early (2013)

#566

Earlier quoted context omitted.

Do they? All the Python folks I've ever seen express an opinion on style have said "follow PEP 8". Unsurprisingly, PEP 8 does have a rule for tabs vs. spaces: https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces (spaces, of course)

The PEP8 myth is quite funny. Almost all people I've met who were repeating "follow the pep8" like a mantra, have never read it. The main idea behind pep8 is: be consistent... however even the python library is not consistent. And it looks like no one cares. There was a great moment to make it nice and consistent - creating the python3, where many incompatible changes were introduced. Instead, the mess is like it was…

> please, go and read pep8

OK. What am I looking for?

Re: Avoid Else, Return Early (2013)

#567

Earlier quoted context omitted.

"Same way comments are extra weight that should only be in public or algorithm/need to know areas. " Best thing I learned about commenting is: Comment WHY you are doing it... not WHAT. Code is the WHAT... Comment is the WHY

If you feel the need to specify in a comment that the code does some potentially unexpected thing or that the way it does what it does has certain consequences, that's fine. And obviously the comment/doc of a function/class/whatever should say what it does if it's not 100% obvious and unambiguous from the name. I don't think this kind of rule is really helpful. Just comment if you feel a comment is needed, and if oth…

People do need to be taught this. I inherited a script from a co-worker who had left. My team leader had gone over it and commented it for me.

    # open file 
    with open(my_file, "rb") as binary_file:
       binary_file.seek(8)  

No mention of what was at byte 8, or what the hell it was doing, but he commented the only obvious part of the code.

Re: Avoid Else, Return Early (2013)

#568
post #351

Earlier quoted context omitted.

I would argue that it is by no means more convoluted. It is quite clear and concise. All of the following are equally readable: if (x > y) { return x; } else { return y; } if (x > y) { return x; } return y; return (x > y) ? x : y; The logic would be convoluted if you are going through extra hoops in order to write your logic like this, making the flow of the application unclear. For some things, an else branch ends u…

The examples are only similar to the extent that they do the same. If you look at what intent they communicate - which is an important part of readability - the second example indicates that x>y is a "special case", which just obscures the simple logic of the function.

I agree that what they communicate is important, but I disagree that the early return communicates "x>y" as a special case.

Nothing about early return indicates a special case, but rather just indicate that a conclusion has been reached. A few examples:

    1. A function that compares two arrays, and first checks if they are null or if their lengths differ before checking their individual elements, and potentially recursing. The early returns are likely to be the hottest section of the function, with the element checking being the special case.
    2. A function that searches a list or tree for a node that matches a set of conditions. All but at most one run will use the early returns, making the corpus of the function the special case.
    3. A function that does some processing, with fast paths that handle the vast majority of data, but a slow path for when the fast paths do not apply. The fast path is an early return, but the slow path is the special case.
In other words, I believe that it is incorrect to consider an early return to be a special-case, and interpreting code like so might result in misunderstandings. You should look at the condition to see if it is a special case. The only thing an early return indicate is that the return value has been decided, and no further processing is needed.

I still think that all my examples communicate the exact same to the reader.

Re: Avoid Else, Return Early (2013)

#569

Earlier quoted context omitted.

There is a ton of code that only exists because of issues elsewhere in the code . This is the opposite of brilliant code: these are the dirty patchworks, the hacks glueing the whole thing together. Yet often these hacks are necessary, at least until some bug is fixed elsewhere. Clear, self-documenting code is great but it can't capture that holistic insight into what the whole program is doing. It can't capture conte…

Also, any non-trivial software project is going to end up needing workarounds for bugs in other software. And you really need to document those. Because otherwise someone is going to remove that second refresh() statement, not knowing that this works around a bug in OS version xyz.

Basically, "IE8 fix"-comments

Re: Avoid Else, Return Early (2013)

#570
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…

> 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. I'm glad to hear a perspective like this. I'm fortunate enough to not come across too many people like this, but I'm always utterly baffled by people who get defensive about the smallest complaints about Javascript (of which t…

Ha, well, not to get too defensive about my past defensiveness, this was at a time where the irrational hatred was constant and unrelenting. Some time after the 'Javascript: The Good Parts' book, but before all the ES6 goodies.

Just a few weeks ago I had some badstalgia when I mentioned I did front-end development to someone. He responded with a rant about how real programmers don't use javascript, and how it was written in ten days, and so on.

But yes, I'm happy to have largely stepped away from the language wars. I occasionally join the #javascript channel on IRC and it's truly astounding how much of the conversation is just people attack or defending javascript passionately, and for very silly reasons.

Post reply on HN