10
l0om
6y

A or B? Fight!

Comments
  • 8
    B because less verbose.
  • 3
    if
    (
    condition
    )
    {
    return x
    }
  • 2
  • 8
    And the correct way is to as few exit points as possible. So assign your value to a variable and return in the end of your fn
  • 2
    Depends on the context.
  • 2
    While it doesn't matter in this example, it's always good practice to use an 'else'. If your statement body doesn't return something, it will always run both statements otherwise. With an else statement, it won't be run, if the first condition is met. Less time to run the code.

    And also I like just using the if statements to assign a variable, and then return it at last, when it's something like this.

    One last thing. 3 is kinda the limit for not using a switch in my opinion. But yeah I'd still consider using a switch. Sorry if it seems like I'm bashing your code, I'm really not 😅
  • 1
    I'm with ReSharper here which reports option a as redundant. Omitting the elses makes the code more easy to read and saves on indents.
  • 1
    @netikras Why? Isn't it just wasting a variable amd storage for thay time, instead just returning seems better. Why do you think multiple exit points is a problem?
  • 1
    @phreakyphoenix not a problem for short functions. But when you have longer ones, 10+ loc, the more exit points a fn has [incl exceptions], the more complex it becomes. We do not want to mainrain complex code, do we?

    Failfast returns are an exception 'cuz they are the first instructiobs to be run/read.

    And the variable.. How much do you relly waste on a single variable assignment? :) it's next to nothing
  • 1
    I have to agree that I like using a variable to have only one exit point in a function, too. But recently I try to make everything as stateless and immutable as possible and here the multiple return statements clearly win.
  • 0
    A, but remove the final else.
Add Comment