14

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)?

Community
  • 1
  • 1
Stripies
  • 1,267
  • 5
  • 19
  • 29
  • 1
    Question seems to be vague. You want to know which is the better way ? – Anuj Balan Dec 01 '11 at 11:05
  • 1
    Duplicates: http://stackoverflow.com/questions/137115/are-multiple-return-points-from-a-method-good-or-bad http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement – bezmax Dec 01 '11 at 11:22

7 Answers7

11

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.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • 1
    I think the persons who developed java does't know about this :P. Because in "most"* code in java have return statement at the end. * the code i seen in JDK – nidhin Dec 01 '11 at 11:18
  • @nidhin - the people who created Java made it possible to return anywhere, they do not enforce this "single return" rule. Try to think "why should there be a single return" and see what reason you can think of. Developers need to decide whether to use nesting or return early on a case by case basis and readability is the best measure for this. – Fenton Dec 01 '11 at 11:20
  • 1
    Basically you *shouldn't need* to improve readability of your code by using early returns. If you do - your code is already a mess and early returns won't help that... much. – bezmax Dec 01 '11 at 11:20
  • By reducing the nesting of the if / else you have already improved the readability. – Fenton Dec 01 '11 at 11:23
  • @Sohnee we are talking about best practice and not about how to return vales from function. By the way i am not the person who down voted your answer :) – nidhin Dec 01 '11 at 11:23
  • @nidhin you still haven't explained the argument in favour of your best practice. As developers, we should use our experience to decide on a case by case basis whether we think the method should return early or a have a single return. There shouldn't be a "best practice" for such a detail - the best practice is to keep your code readable and you will get a different answer to this question depending on the specific method you are writing. Best practices do not exist at such a low level. – Fenton Dec 01 '11 at 11:28
  • What do all of you mean by single return? Where would the single return be placed in a function? – Stripies Dec 01 '11 at 11:32
  • 1
    @user1075261 by "single return" we mean that the method only ever exits in a single place, not necessarily using a return statement as in this question it returns when it gets to the end (or if you place an additional return statement inside the method). – Fenton Dec 01 '11 at 11:35
  • It may be advisable to move this discussion to an existing question of which this is a duplicate: http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement – Fenton Dec 01 '11 at 11:37
  • @Sohnee Where did the single return rule come from? – Stripies Dec 01 '11 at 11:38
  • 1
    @user1075261 - it is useful in managed languages, as you are concerned about allocation and de-allocation of memory. For this reason it was usual for methods to be carefully ordered, with the return statement last. – Fenton Dec 01 '11 at 11:39
9

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.

Alpedar
  • 1,314
  • 1
  • 8
  • 12
  • 5
    Used -1 because I generally would prefer a return statement over code that performs if/switch statements just to get to the end of the method. I'm of course fully in favour of refactoring once things get complicated. Also, bad input should result in exceptions, not early returns. This is not made clear enough in the answer. – Maarten Bodewes Dec 29 '11 at 16:01
  • Bad input -> exception, but sometimes there is trivial input -> trivial return (eg. 1! = 1). – Alpedar Dec 29 '11 at 19:00
1
  1. For the best practice the return statement should be the last line of function

  2. Using else block is good method because if you want to add some other code in future the first block of code may need editing

note: All methods have it's on merits and cons. Their is no Silver bullet solution.

nidhin
  • 6,661
  • 6
  • 32
  • 50
  • 4
    That is a very absolute statement. A lot of the time an early return will prevent a complex and nested control-flow and would therefor be preferable over a single return. – Mark Rotteveel Dec 01 '11 at 11:09
  • 1
    @MarkRotteveel: Not really. If you find your code structure too complex and nested while using 'last line return' style - that means you need to refactor your code. Usually that means moving validation out of business logic or similar stuff. – bezmax Dec 01 '11 at 11:12
  • Eclipse actually whines if you have ”pointless” else (an if where is return clause and nothing else). – Smar Dec 01 '11 at 11:12
  • 3
    I agree with Mark. Sticking absolutely on rules such as "only one return in the end" or "don't jump of loops" can cause complicated code. However, the reason for "breaking" these rules must one be readability and understandability, but never laziness of the programmer. – Heiko Schmitz Dec 01 '11 at 11:15
  • @Max if you write methods with standards that won't be complex in most cases because the number of lines in a method should be minimum. eg. JDK souce code – nidhin Dec 01 '11 at 11:16
1

The second is preferred since methods should have only one return statement and it must be at the end of the method itself. If you want to go deeper on that topic, there are many programs that do validations over your code. One of these is PMD. There is also a useful eclipse plugin to validate your code against the conventions you are looking for.

loscuropresagio
  • 1,922
  • 15
  • 26
1

Once you hit the return the method ends and returns to the calling method in the stack.

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

and

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

will do the same, but AFAIK it's preferred for any method to have only one exit point (at least it's what Edsger Dijkstra says)

Averroes
  • 4,168
  • 6
  • 50
  • 63
0

No, you can use both ways. First way is also used when you have many other conditions, and return will move you out from method. In this way you have no nested conditions.

Hleb
  • 295
  • 1
  • 4
  • 15
0

Either code snippet will work. It will depend on the context in which the code is being used.

Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
Matt Seymour
  • 8,880
  • 7
  • 60
  • 101