2

I'm writing a few very long functions that have to check values and return true if a specific pattern has been found. I'm performing if check and returning false after one condition fails, never using the else part like in this example

if (a < 0) {
    return false;
}
// code
if (b < 0) {
    return false;
}
// code
if (a + b / c > d) {
    return false;
}
// code

Is this the correct approach or should I use else instead? Is there any difference in performance or is it just a matter of readability?

if (a < 0) {
    return false;
} else {
    // code
    if (b < 0) {
        return false;
    } else {
        // code
        if (a + b / c > d) {
            return false;
        } else {
            // code
        }
    }
}
Naigel
  • 9,086
  • 16
  • 65
  • 106
  • 7
    Related? http://stackoverflow.com/q/14102954/447156 – Soner Gönül Jul 29 '15 at 11:59
  • 2
    FWIW, ReSharper marks each of your `else` statements as redundant. – James Thorpe Jul 29 '15 at 11:59
  • 1
    I would say what you are currently doing is fine, it's more readable and you are not nesting If statements, this will also allow it to have better maintainability – Jamie Rees Jul 29 '15 at 12:00
  • I would use the former, unless I was aiming for a single point of return. In which case the else is required. There's no difference in performance. – James Jul 29 '15 at 12:02
  • 3
    Why not use if (a < 0 || b < 0 || (a + b/ c > d)) return false. This is also evaluated from the left, so also same performance. – Arno van Lieshout Jul 29 '15 at 12:03
  • 1
    @SonerGönül thank you, that is the answer to my question @JamesThorpe this is a good confirmation Please note this is an example, in the "real code" variables are elaborated the re-evaluated, I can't collapse all in a single `if` statement – Naigel Jul 29 '15 at 12:21

3 Answers3

2

I think the example you have given is just for demonstrations purposes. However, in general, it's just a matter of readability, there is no performance difference as compiler does the optimizations. Personnally I prefer the way you have done it by returning. If you have a longer logic it's more readable to understand certain invalid scenarios. And also cleaner than nested if/else blocks. Just my opinion.

CharithJ
  • 46,289
  • 20
  • 116
  • 131
-1

Your initial if without else was pretty correct but this:is short readable and efficient

if (a < 0 && b < 0 && (a + b)/ c > d)
 {
    return false;
} else
{
  • 1
    This logic is incorrect, you should be using `||` instead of `&&`. You've also changed the final expression, `a + b / c > d` would be evaluated as `a + (b / c) > d` – Alex Neves Jul 29 '15 at 12:22
-1

if else is not required then i will use below code. If it is required then i will prefer answer mentioned by DeshDeep.

I will prefer as there is less line of code but it is depend on individual choice.

if (a < 0 || b <0 || (a + b / c > d)) {
    return false;
}