Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - return or if-else [duplicate]

Possible Duplicate:
Should a function have only one return statement?

This is what I am talking about.

if (condition) {
    aVariable = 1;
    return;
}
doSomething();

if (condition) {
    aVariable = 1;
} else {
    doSomething();
}

Is one of these preferred over the other (conventions, etc)?

like image 774
Stripies Avatar asked Dec 01 '11 11:12

Stripies


People also ask

Can we use return in if else statement?

Every return statement is inside an if statement. While it may be logically impossible as written, the compiler needs a return for when none of the if evaluate true.

Should I use if else or return?

It depends on the semantics of your code, if the else branch is the point of the method, i.e. it's named after what happens in the else branch, the early return is probably correct, especially if the first part is some sort of check.

What does return do in IF statement Java?

The return here is probably used in order to "improve" the performance of the method, so that other comparisons are not executed, once the needed scenario is performed.

Can we write return statement in if block?

Is it possible to write return statement in if block? It is possible, but you haven't covered all the possible cases to which the program flow may go.


2 Answers

Returning early can improve readability by reducing nesting in your code.

In some languages it is best practice to have a single return statement, for example in C++ you should allocate at the top and de-allocate at the bottom of your method, but Java is not such a language so prefer readability over a single return statement.

Many people use the single return rule because they don't understand why it exists or because they have a background in managed languages.

Please Note

Before you comment about the "one true way" of writing code, please pause for a moment and consider the following.

Why must there be only a single return statement?

If you can't think of a good reason, stop arguing that it should be the case.

like image 108
Fenton Avatar answered Sep 20 '22 14:09

Fenton


Readability is most important. So early returns on begining of functions are ok, but once method starts doing something more complicated than checking its imputs/state of object, it should have only one return .

And if it is too complicated, it should be refactored to multiple functions.

like image 23
Alpedar Avatar answered Sep 17 '22 14:09

Alpedar