62

Listen. Use invariants. If you can do

if(!x) {
return foo;
}
...rest of function logic...

Instead of

if(x) {
...some long branch with more tests...
} else {
return foo;
}

Please do. It's so much easier to read when all of your conditions are tested in a line at the top instead of nested 8 layers deep in if-else blocks.

Thanks

Comments
  • 11
    Someone somewhere around here also ranted about a block of code with multiple return points being hard to understand and debug.

    ...

    Just avoid code smell. You can't hide it if it's there.

    And avoid using ellipsis as often as I do.
  • 11
    Or more succinctly: Guards up!
  • 3
    Aren't those called early returns?
  • 6
    @Root Are you from Person of Interest ?
  • 6
    @riteshx95 Why of course not, Harold. I would never. 🙂
  • 3
    @Pointer where I work, we call them early exit
  • 6
    @Root You sound like her too .. 😂😂
  • 3
    @riteshx95 Huge compliment ❤
  • 2
    @metrobug Defensive programming means assert your assumptions at the outset. While that's one application of this idea, it's not the only one. The core idea is just shaking your logic tree out so that it requires less indentation, if you can do so cleanly.
  • 1
    Not really sure if you mean use early exits or whatever theyre called or to seperate logic or validation in seperate methods.

    Either way, I try to avoid multiple returns spread across a method. It makes it harder to read for me.
  • 2
    @Ederbit This is not best practice in every application. If you don't use guards at all, you'll usually end up with a lot of nested branches and/or a lot code getting executed unnecessarily
  • 1
    @Ederbit pretty much just what @AndSoWeCode said
  • 2
    @aaxa I precisely mean what @AndSoWeCode said. But I didn't mean to leave out defensive programming. :)
  • 1
    I don’t mind early exit or multiple return, in fact in a language like F# multiple return is largely a given.

    I think it’s possible to get it horribly wrong and go over the top though.

    I do however always try to invert conditionals if it means I can avoid nesting.
Add Comment