10

I have found myself using the following practice, but something inside me kind of cringes every time i use it. Basically, it's a precondition test on the parameters to determine if the actual work should be done.

public static void doSomething(List<String> things)
{
    if(things == null || things.size() <= 0)
        return;

    //...snip... do actual work
}
aglassman
  • 2,643
  • 1
  • 17
  • 30
  • 1
    Use a tool like PMD, Checkstyle or FindBugs to have a third opinion, then search about it. IMHO, it's not a bad practice as long as is considered under your coding standards. – Luiggi Mendoza Mar 20 '13 at 15:16
  • 5
    You can read a long thread here: http://programmers.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement – PeterMmm Mar 20 '13 at 15:16
  • This has got to be a duplicate. Try searching for the answer. – Ash Burlaczenko Mar 20 '13 at 15:16
  • If it makes *you* cringe, it might not be the right method for *you*. – akaIDIOT Mar 20 '13 at 15:17
  • Did a quick search, but wasn't sure how to word it. Thanks for the link to the thread, exactly what I was looking for. – aglassman Mar 20 '13 at 15:18
  • The way I see it is that you either do this or check the parameters before calling the function, which your method seems a bit easier to code. – David Starkey Mar 20 '13 at 15:21
  • 2
    The "return only once" argument over again. Not really relevant with Java as it's common practice to return multiple times. – Steve Kuo Mar 20 '13 at 16:27
  • Duplicate of: http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement?lq=1 – Johan Jul 06 '13 at 20:10
  • **Simplicity and efficiency is better.** So which one do you think is more simple? (Early returns) – Tom Burris Aug 15 '16 at 08:44

11 Answers11

17

It is good practice to return at the earliest opportunity.
That way the least amount of code gets executed and evaluated.

Code that does not run cannot be in error.

Furthermore it makes the function easier to read, because you do not have to deal with all the cases that do not apply anymore.

Compare the following code

private Date someMethod(Boolean test) {
  Date result;
  if (null == test) {
    result = null
  } else {
    result = test ? something : other;
  }
  return result;
} 

vs

private Date someMethod(Boolean test) {

  if (null == test) { 
    return null 
  }
  return test ? something : other;
} 

The second one is shorter, does not need an else and does not need the temp variable.

Note that in Java the return statement exits the function right away; in other languages (e.g. Pascal) the almost equivalent code result:= something; does not return.
Because of this fact it is customary to return at many points in Java methods.
Calling this bad practice is ignoring the fact that that particular train has long since left the station in Java.

If you are going to exit a function at many points in a function anyway, it's best to exit at the earliest opportunity

Johan
  • 74,508
  • 24
  • 191
  • 319
  • This makes sense. I wasn't aware that some languages may not exit the function upon return. This sheds a new light on why it may be considered a 'bad practice' by some developers, and not by others. – aglassman Mar 21 '13 at 14:26
  • The first example is actually smelly but because of the way you write it, if you code it right, it is equally readble and easier to follow the flow than your second one: private Date someMethod(Boolean test) { Date result = null; if (test != null) { result = test ? something : other; } return result; } – Pau May 13 '13 at 14:08
  • -1. Code that does not run can certainly be in error. If code to add my deposit to a bank does not run that is an error. As for the actual question, I agree with the early return, just not for your reasons. – user949300 Jul 06 '13 at 22:05
4

It's a matter of style and personal preference. There's nothing wrong with it.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
4

To the best of my understanding - no.

For the sake of easier debugging there should be only one return/exit point in a subroutine, method or function.

With such approach your program may become longer and less readable, but while debugging you can put a break point at the exit and always see the state of what you return. For example you can log the state of all local variables - it may be really helpful for troubleshooting.

It looks like there a two "schools" - one says "return as early as possible", whereas another one says "there should be only one return/exit point in a program".

I am a proponent of the first one, though in practice sometimes follow the second one, just to save time.

Also, do not forget about exceptions. Very often the fact that you have to return from a method early means that you are in an exceptional situation. In your example I think throwing an exception is more appropriate.

Alex Kreutznaer
  • 1,170
  • 8
  • 18
  • 1
    So you want to sacrifice readability for debugability? Also if your throw an exception that will messup your single debug breakpoint theory, because an exception is just another return path. – Steve Kuo Mar 20 '13 at 22:54
  • 1
    @SteveKuo As I already said there is no way to select one universal approach here, it's a trade off whatever you select. Return - for normal execution flow, exceptions for exceptional situations. With exceptions you can always see the stack trace. Single return point let you find logical bugs, rather than technical. – Alex Kreutznaer Mar 21 '13 at 02:29
2

PMD seems to think so, and that you should always let your methods run to the end, however, for certain quick sanity checks, I still use premature return statements.

It does impair the readability of the method a little, but in some cases that can be better than adding yet another if statement or other means by which to run the method to the end for all cases.

Nova Entropy
  • 5,727
  • 1
  • 19
  • 32
2

There's nothing inherently wrong with it, but if it makes you cringe, you could throw an IllegalArgumentException instead. In some cases, that's more accurate. It could, however, result in a bunch of code that look this whenever you call doSomething:

try {
    doSomething(myList);
} catch (IllegalArgumentException e) {}
raptortech97
  • 507
  • 3
  • 14
  • Why would you throw exceptions all over the place? – Johan Mar 20 '13 at 20:19
  • @Johan I wouldn't in most cases, but in situations where an early return doesn't make sense, an exception might make more sense. – raptortech97 Mar 21 '13 at 13:40
  • @raptortech97: +1 for thinking outside the box and mentioning throwing an Exception, -1 for semi-suggesting catching it and doing nothing all over the place. Just as easy to check before calling if doing nothing makes sense when it's null. – jmoreno Sep 12 '14 at 06:03
2

There is no correct answer to this question, it is a matter of taste.

In the specific example above there may be better ways of enforcing a pre-condition, but I view the general pattern of multiple early returns as akin to guards in functional programming.

I personally have no issue with this style - I think it can result in cleaner code. Trying contort everything to have a single exit point can increase verbosity and reduce readability.

henry
  • 5,923
  • 29
  • 46
1

It's good practice. So continue with your good work.

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59
0

There is nothing wrong with it. Personally, I would use else statement to execute the rest of the function, and let it return naturally.

mike.tihonchik
  • 6,855
  • 3
  • 32
  • 47
0

If you want to avoid the "return" in your method : maybe you could use a subClass of Exception of your own and handle it in your method's call ?

For example :

public static void doSomething(List<String> things) throws MyExceptionIfThingsIsEmpty {
    if(things == null || things.size() <= 0)
        throw new MyExceptionIfThingsIsEmpty(1, "Error, the list is empty !");    

    //...snip... do actual work
}

Edit : If you don't want to use the "return" statement, you could do the opposite in the if() :

if(things != null && things.size() > 0)
// do your things
Guillaume M
  • 470
  • 1
  • 5
  • 12
  • 3
    this would be an "over complication" IMHO, because now he has to worry about catching the exception; and he never stated he really cared to know that the event occured – mike.tihonchik Mar 20 '13 at 16:01
  • And throwing an exception is another return path, so you still have multiple returns – Steve Kuo Mar 21 '13 at 00:22
0

If function is long (say, 20 lines or more), then, it is good to return for few error conditions in the beginning so that reader of code can focus on logic when reading rest of the function. If function is small (say 5 lines or less), then return statements in the beginning can be distracting for reader.

So, decision should be based on primarily on whether the function becomes more readable or less readable.

Wand Maker
  • 18,476
  • 8
  • 53
  • 87
-1

Java good practices say that, as often as possible, return statements should be unique and written at the end of the method. To control what you return, use a variable. However, for returning from a void method, like the example you use, what I'd do would be perform the check in a middle method used only for such purpose. Anyway, don't take this too serious - keywords like continue should never be used according to Java good practices, but they're there, inside your scope.

  • http://java.dzone.com/articles/common-code-violations-java http://stackoverflow.com/questions/884429/better-java-method-syntax-return-early-or-late http://programmers.stackexchange.com/questions/118703/where-did-the-notion-of-one-return-only-come-from – Jorge Antonio Díaz-Benito Mar 20 '13 at 18:11
  • @AlexKreutznaer First, given that the rules of SO state that preferred questions are 'the ones that can be answered', not discussions, and that this one is a duplicated one (see [this one](http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement), as an example, and I'm sure it's not the only one) if you're really looking for downvoting somebody, go do it with the person who asked, not me, because I've been the only one providing some links when asked, when there are others, one-line, no reference, even upvoted. I-see-a-child-pic-I-downvote'rs make me sick. – Jorge Antonio Díaz-Benito Mar 20 '13 at 20:30
  • @Jorge Antonio Díaz-Benito I don't remember that I ever down voted anyone. Your statement is more than questionable. There is no agreement which approach is better. Please, don't be so sensitive when someone objects you, you don't know me, and the first time I objected you, you started talking about "down voting". – Alex Kreutznaer Mar 20 '13 at 20:35
  • For the record it was me who downvoted. I downvoted, because you claim a fact without citing a reference. – Johan Mar 20 '13 at 20:38
  • HanletEscaño Nobody, me included is giving a strong, definitive reason backing up their responses. So that mine is opposite to almost all of them isn't a reason for it to be wrong. In fact, the one I consider the most solid (tristan2468's one) is based on PMD and thinks like I do. @AlexKreutznaer Sorry, I saw the downvote and your comment and mis-associated. I'm, however, still against the downvote Johan, ¿please could you explain me what makes my answer specially less useful than most of others? – Jorge Antonio Díaz-Benito Mar 20 '13 at 20:45
  • @Jorge Antonio Díaz-Benito If you use word like this: "...that's a lie/mistake" or "you're really looking for downvoting somebody", while talking to a complete stranger, be ready people will down vote you. You probably are a young man. Just relax. Get my up vote, just to let you know that nobody is against you here. – Alex Kreutznaer Mar 20 '13 at 20:50
  • @Jorge Antonio Díaz-Benito by the way - my opinion is exactly the same as yours. There should be only one exit point in a method/function/subroutine. – Alex Kreutznaer Mar 20 '13 at 20:55
  • AlexKreutznaer This place is not a quest for reputation, or at least not for me. What I can't understand is why @Johan tags my answer as not useful. If he could provide me an explanation I'd try to improve my future answers so they're not useless like this. I use to justify all my upvotes and explain why I disagree with an answer/think that a question/answer should be downvoted. – Jorge Antonio Díaz-Benito Mar 20 '13 at 21:01
  • 1
    @JorgeAntonioDíaz-Benito i downvoted because you state the answer as a fact without listing a reference. Personally I would like to see a reference for the best practise. I always enjoy reading about coding styles/coding advice but none of that is currently in your answer. – Johan Mar 20 '13 at 21:41
  • From your own linked stackexchange reference "SESE often makes code more complex. So it is a dinosaur that (except for C) does not fit well into most of today's languages. Instead of helping the understandability of code, it hinders it." – Steve Kuo Mar 21 '13 at 00:30
  • 1
    @SteveKuo Methods shouldn't be very long. In this case, yes it messes things up. If methods are long it probably means that something is wrong with the code granularity. – Alex Kreutznaer Mar 21 '13 at 02:34