0
public boolean percentDepreciatedOutOfRange() {
    if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
        return true;
    }
    else {
        return false;
    }
}

Can the code above be written without the else statement and just have return false; after the if statement and still have the same result? If so, why? This is what I mean

public boolean percentDepreciatedOutOfRange() {
    if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
        return true;
    }
    return false;
}
1
  • 3
    Yep. Both mean the same. Oct 18, 2014 at 6:21

3 Answers 3

4

You should just write

public boolean percentDepreciatedOutOfRange() {
    return percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX);
}

which is more readable. Avoid statements like

If (xxx) { return true; }
else { return false; }

because the if just adds noise around the expression.

The reason why this is legal is that the boolean type is the same in evaluating the if expression and in the return type of the method.

1

Because return actually exits the function (method).

In the case the if is not entered the rest of the code will execute normally.

Since you have boolean returns, having return false at the end of the function, means everything up to the end failed.

You could even rewrite it to:

public boolean percentDepreciatedOutOfRange() {
    if (percentDepreciated < DEPRECIATION_MIN) {
        return true;
    }
    if (percentDepreciated > DEPRECIATION_MAX) {
        return true;
    }

    return false;
}

To clearly state the tests in the method.

0

Another way I like:

  1. Defining return variable as 1st statement with default value.
  2. Change the variable in method in various biz logic
  3. Return the variable value (Single return statement)

    public boolean percentDepreciatedOutOfRange() { boolean status = false; status = percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX; return status; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.