Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm also a fan of early exits, for more reasons than in the post: an early return results in less nestings and less variables, it makes the code simpler. Consider:

    Option<T> sink(int pos) {
        if(pos>=this.length()){
          return Nope;
        }
        // code that has depends on the bounds check
        Some(value)
     }
Versus:

      Option<T> sink(int pos){
         Option<T> ret = Nope
         if(pos < this.length()) {
             // same code
             ret = Some(value)
         }
         return ret;
     }
I argue that the second is more complex: an added variable, deeper nesting, useless return line.

When rewriting multiple guards you get more empty statements that reassign the default value of the return.

I do have the following opposite opinion too: guards should be simple: no loops, no complex control flow (name the loop). No side effects in guards. And no guards handled by the expected case, even for clarification.



  return pos < this.length() ? Some(value) : Nope
See, mine is already way more simple than yours. This is my point, if you force yourself not to use jumps, you will end up with simpler and better programs. Also the second example you wrote is expressive and more importantly you can move that code. Also note that in many other programming language like lisp and haskell, you would never need the intermediate variable as you can basically write return if...


The comment twice stands for some complex logic with side-effects which calculates value. You shouldn't put that in a ternary if, in most languages you can't.

And even then I would reverse the order, placing the exceptional and short case first.

Moving the code: why? You have a perfectly encapsulated function. If you need to, you have more problems with shadowing variables, functions and with return types.

For functional languages: doesn't Haskell explicitly have guard pattern? I thought the general guidelines favored matching and guards over if statements.


But that requires you to have the output assigned to a variable even without valid input..


This whole guard/validation thing is a fabrication of the mind. Because early returns do returns something on an invalid input. If anything, those validations should be asserts/exceptions.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: