aspose file tools*
The moose likes Beginning Java and the fly likes Coding standards discussion - particularly multiple 'return's Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Coding standards discussion - particularly multiple Watch "Coding standards discussion - particularly multiple New topic
Author

Coding standards discussion - particularly multiple 'return's

James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

In my opinion Ivan, it is cleaner code to have a single return statement within a method. It makes the code easier to read and debug.

Let's say I am debugging and I want to investigate the return value from a method. Simple, I go straight to the final line in the method (the single return statement), set a breakpoint and start the debugger. Now, if I have multiple returns, that is not so easy and I will need to set multiple breakpoints.

My only exception to this rule would be a guard statement at the start of the method:

Ivan Jozsef Balazs
Rancher

Joined: May 22, 2012
Posts: 877
    
    5
In my opinion Ivan, it is cleaner code to have a single return statement within a method. It makes the code easier to read and debug.


I do not agree with you.

Let us imagine my example with more guard statements etc. with only one positive return branch.
How would you organize that code? As a huge nested if?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18911
    
    8

I have written switch statements in which each of the cases returns a different value. Personally I wouldn't think that modifying that to have each of the cases assign a different value to a local variable followed by a single statement returning that value improved the readability at all.

However I do sympathize with your debugging example. But I generally don't write my code to simplify debugging; I have often replaced something like this:



by



so that I can put a breakpoint on the return statement and find out what's being returned from the method. You didn't say you would write your code like the latter version and leave it that way, but your example sort of suggested you would.

James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

Paul

I personally have no preference whether the return statement is a calculation or the value of a local. Just the fact that I know there is only one and it is at the end.

Anyway, I feel the end of this topic is going off topic so best to leave it there. It is only my opinion, everyone is entitled to their own.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39884
    
  28
James Boswell wrote:In my opinion Ivan, it is cleaner code to have a single return statement within a method. It makes the code easier to read and debug.
Agree. But I know this is a controversial point and some people will disagree.
My only exception to this rule would be a guard statement at the start of the method:

Disagree. It is dangerous to let nulls into your code. I am not convinced that is a guard, which was defined by E W Dijkstra the best part of 40 years ago. In case of a false guard, the following code become infeasible and execution stops. What you have there is a branch. The nearest you can get to a guard in Java™ is this:-Much better practice
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

Nice javadocs Campbell!

I think there is a case for returning null rather than throwing an exception. As long as the method is documented appropriately, the caller knows what to expect.

Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

James Boswell wrote:Developers who think it is OK to call static methods via instances of a class probably think it is OK to use:
- One line, no brace condition statements
- Multiple returns in a method
- Return statements in a void method
- Different naming standards to those set out in the original Java tutorials (as mentioned by Tony)
- Business logic within exception blocks

Guilty of all the above, I'm afraid; and happily so. Also guilty of single-line method definitions, particularly for forwarders. I let my IDE formatting worry about stuff like that.

I'd say that what's more important is, if you vary from an accepted standard, that you can justify your decision.

I think there is a case for returning null rather than throwing an exception. As long as the method is documented appropriately, the caller knows what to expect.

Which just goes to show that everyone has their own standards. Personally, I hate returning nulls because I hate NPEs; and I particularly hate propagating them, which is what your example does.

There are cases where it's difficult not to return a null; but in those situations, I generally try to document it VERY LOUDLY.

Winston

Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

Winston


- Return statements in a void method
- Business logic within exception blocks


Guilty of these? Really?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

I love the style a number of functional languages (e.g. SML & Scala) deal with the "returning null" issue. You return an option type, which can encapsulate a value or the lack of one. But the important part is that, because of the pattern matching approach they use, the compiler can force you to handle the case where there is no value.

In Java, I'll return null whenever it seems the most appropriate thing to do. Which, I find, isn't remotely rare.

This is going way off topic
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

James Boswell wrote:

- Return statements in a void method
- Business logic within exception blocks


Guilty of these? Really?
The first isn't that unusual. I can show you a few examples from the standard Java libraries that do that. And no, I'm not holding them up as a paragon of design, but if they do something it can't be that surprising if others do it as well.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

James Boswell wrote:Winston

- Return statements in a void method
- Business logic within exception blocks
Guilty of these? Really?

Sure. I don't agree with the "only one return statement" thing anyway; it smacks of '60's thinking. So, why shouldn't I return if I don't want to execute a scad of code? It often means you can avoid "negative" logic too, which I dislike far more than multiple returns.

Classic case in point (admittedly not with a void):
The latter: if I can reasonably expect to recover from an exception, and that involves business logic, then that's exactly what I'll do.

Winston
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39884
    
  28
Does that mean plain simple return; ? All that does is return control to the calling method. Which can be just as confusing if it isn't the last line in the method.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

Campbell Ritchie wrote:Does that mean plain simple return; ? All that does is return control to the calling method. Which can be just as confusing if it isn't the last line in the method.

If that was directed at me then: yes.

Confusion is in the eye of the beholder; and my general rule of thumb is to make my method as easy to follow as possible. I'm less worried about anyone trying to do flow-path analysis on stuff that might be calling it.

Winston

PS: I should probably add that I don't generally like methods that return void; so if I write them, they're usually private.
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

At this point, I'm going to apologise to the OP for hijacking this topic - not my intention.

I will air my opinions at a more appropriate time in future
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

James Boswell wrote:At this point, I'm going to apologise to the OP for hijacking this topic - not my intention.
I will air my opinions at a more appropriate time in future

No probs. That's what happens sometimes. However, I'm quite happy to split this discussion to a separate topic if you prefer.

Winston
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

I just feel a return statement within a void method is wrong - the method does not return anything. When the execution flow returns from a void method, it should either have run to completion or thrown an exception.

An exception block should unlock resources, log the exception or throw a more application-specific exception. Nothing more.

Just my opinions. Right, I'm done on this one, no more from me.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

James Boswell wrote:I just feel a return statement within a void method is wrong - the method does not return anything. When the execution flow returns from a void method, it should either have run to completion or thrown an exception.

An exception block should unlock resources, log the exception or throw a more application-specific exception. Nothing more.

Just my opinions. Right, I'm done on this one, no more from me.

For anyone who's been following this discussion, I've split it off from the original thread, so further comments are welcome.

@James: I'd say your standards are a bit OTT, but that's just my opinion.

Programming is a creative process, hopefully done by people who are reasonably intelligent; so words like 'never' or 'always' have no business in it, or even in standards about it. Except maybe for beginners.

The general focus of all the things we've been discussing is clarity, so the acid test is: do other people understand your code? If so, you probably did your job right, whether you adhered to "standards" or not.

Winston
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5


The general focus of all the things we've been discussing is clarity, so the acid test is: do other people understand your code? If so, you probably did your job right.

I totally agree with this statement. I guess people have different ways (opinions) on how to achieve this goal.

Thanks for moving the thread but ironically, it might come to an end now.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39884
    
  28
Not quite finished. Agree with Winston about documentation. Can you tell from the documentation for String#indexOf(java.lang.String) that it throws an NPE if you pass null?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39884
    
  28
James Boswell wrote:Nice javadocs Campbell! . . .
Thank you
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14352
    
  22

Matthew Brown wrote:I love the style a number of functional languages (e.g. SML & Scala) deal with the "returning null" issue. You return an option type, which can encapsulate a value or the lack of one. But the important part is that, because of the pattern matching approach they use, the compiler can force you to handle the case where there is no value.

In Java, I'll return null whenever it seems the most appropriate thing to do. Which, I find, isn't remotely rare.

This is going way off topic

In Scala, or in functional programming languages in general, you should not use the return keyword at all - I regard it as a code smell when I see it in Scala code. The return value of a method or function is just the value last expression in the method or function.

On topic: I have no problem with multiple returns in a method. But if you feel you need to do this for something else other than in the beginning of the method (for example to return early when some argument check fails), then that is a sign that the method is too complicated or has a bad structure or that it does more than one thing, so it needs to be refactored.

I remember fixing a bug where a method did an early return somewhere in a nested if block, but there was some more logic after the block which should have been executed but wasn't because of the early return. That was clearly an example of a method that was trying to do too much, and which needed to be split up into several smaller methods that each did one thing.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

Jesper de Jong wrote:
In Scala, or in functional programming languages in general, you should not use the return keyword at all - I regard it as a code smell when I see it in Scala code. The return value of a method or function is just the value last expression in the method or function.

Oh, I agree, I was using "return" in the looser sense.
Ivan Jozsef Balazs
Rancher

Joined: May 22, 2012
Posts: 877
    
    5
Return statements in a void method


I must admit to be guilty in this point too.

For example if some check condition is met in a doGet or doPost method of a servlet, which precludes further processing?
Let us set the status and return.
It is the clearest expression of the programer's intent which corresponds to the business logic.



Of course you could either factor out the whole continuation into a method, or put it into the else branch,
but for me it is quite OK (and even better) if the continuation comes normally on the method (indentation) level.

YMM of course V.

Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

Jesper de Jong wrote:On topic: I have no problem with multiple returns in a method. But if you feel you need to do this for something else other than in the beginning of the method (for example to return early when some argument check fails), then that is a sign that the method is too complicated or has a bad structure or that it does more than one thing, so it needs to be refactored.

Ah, well then you'd probably be violating the "page of code" rule, wouldn't you?

However, I completely agree with your general statement.

My only wrinkle is that I detest "negative" logic, especially when it's used in compound expressions - it just does my head in, and I'll go a long way to avoid it (for me, '!'s are just too easy to miss when you're scanning) - so if I have something that I can eliminate quickly and simply, I'll favour a 'return' of any flavour over compounded if's.

Winston
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

Ivan Jozsef Balazs wrote:For example if some check condition is met in a doGet or doPost method of a servlet, which precludes further processing?
Let us set the status and return.
It is the clearest expression of the programer's intent which corresponds to the business logic.

Yup. I wholeheartedly agree.

I think it comes back to basic clarity: Does the code show the intent?

Winston
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

Jesper de Jong wrote:In Scala, or in functional programming languages in general, you should not use the return keyword at all - I regard it as a code smell when I see it in Scala code. The return value of a method or function is just the value last expression in the method or function.

Not being familiar with Scala, I'm on thin ground here; but doesn't saying "no returns" equate to the same thing as "only one return" in a language like Java?

Winston
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

Ivan

I don't see how a variation of your example lessens the programmer's intent:
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

James Boswell wrote:I don't see how a variation of your example lessens the programmer's intent:

I do. Now, quite possibly, your entire logic is part of an 'else' block, which is redundant anyway.

There are obvious limits to all of the things I've been saying (or agreeing with): not the least of which is Jesper's advice to make sure that your method isn't overly complex.

That said, methods (even functional ones) aren't binary. They may return many possible values, for many reasons, and I think all we're discussing is how you illustrate those best.

Winston
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39884
    
  28
But it is usually easier to read code written as if (b) ... else ...
… and harder to read if (!b) ... else ...
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

Winston Gutkowski wrote:Not being familiar with Scala, I'm on thin ground here; but doesn't saying "no returns" equate to the same thing as "only one return" in a language like Java?


The point with a functional language is that every function is an expression, not a set of instructions. return is an imperative concept, and using it suggests a failure to embrace the functional style. Think of it as the equivalent of putting everything in static methods in Java: you can make it work, and you can even make it nicely structured, but it's still not right! .
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

Matthew Brown wrote:The point with a functional language is that every function is an expression, not a set of instructions. return is an imperative concept, and using it suggests a failure to embrace the functional style.

Ah, OK. Thanks Matthew.

So how do you indicate some failure in your "function"; or is the assumption that it can't happen because it will have already occurred somewhere further up the chain? [Edit: that doesn't compute, but hopefully you understand my question ]

Winston
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5


But it is usually easier to read code written as if (b) ... else ... … and harder to read if (!b) ... else ...

Campbell, agreed.

However, adding an else block to the code doesn't make less readable. The method perfectly maps to the pseudocode:

if token contains expected value
do stuff
else
send 403 response
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

James Boswell wrote:However, adding an else block to the code doesn't make less readable. The method perfectly maps to the pseudocode:

But it does add indentation. So, if either of your blocks contains similar logic, you're going to double it up again?

It's straightforward to me: if the condition is one that can occur frequently, and not necessarily in the same method, yank it out; but don't force me to "scan right" simply because you've decided that multiple returns are bad.

Most of the examples we're talking about are straightforward elimination (as in my equals() example above). So do it. I don't want to have to write:simply because someone decided I can't write multiple return statements. It's ludicrous.

Winston
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
Winston Gutkowski wrote:
Jesper de Jong wrote:In Scala, or in functional programming languages in general, you should not use the return keyword at all - I regard it as a code smell when I see it in Scala code. The return value of a method or function is just the value last expression in the method or function.

Not being familiar with Scala, I'm on thin ground here; but doesn't saying "no returns" equate to the same thing as "only one return" in a language like Java?

Not really. Here's an example, using Java-like syntax except for the "return value is the last expression" part from Scala:

This would be equivalent to:

The multiple return values are inherent in any code that ends in multiple branch paths.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

Mike Simmons wrote:Not really. Here's an example, using Java-like syntax except for the "return value is the last expression" part from Scala

Another 'Ah'. Thanks Mike.

Winston
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5


But it does add indentation. So, if either of your blocks contains similar logic, you're going to double it up again?

Winston, excuse my stupidity but I'm not sure I understand you here. Too much indentation can be a pain but not in this example.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

James Boswell wrote:Winston, excuse my stupidity but I'm not sure I understand you here. Too much indentation can be a pain but not in this example.

But it's unnecessary. And your example is binary.

Java methods don't have any in-built smarts to know when we're calling them incorrectly, so it's quite possible that some of the initial code will simply be checking that parameters are OK. Personally, I'm in favour of throwing Exceptions in all invalid cases (especially nulls), but there are cases where you might be able to simply return a reasonable value.

And if you won't accept my equals() example, how about a:
compareArrays(a1, a2)
method?

If the two arrays are identical, it just makes sense for me to return 0 (or true) immediately. What's the fuss? I can't think of anything clearer than:
if (a1 == a2) return 0;
and then continue on if it ain't the case (not indented). Indeed, a second check might be:
Winston
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1030
    
    5

Winston

You make some valid points. Like we said earlier, everyone has their opinions about our craft.

I look forward to hijacking future topics
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14352
    
  22

Winston Gutkowski wrote:Not being familiar with Scala, I'm on thin ground here; but doesn't saying "no returns" equate to the same thing as "only one return" in a language like Java?

In Scala, like in most functional programming languages, everything is an expression (you don't really have statements, just expressions), for example, "if" is also an expression - it returns a value (unlike in Java, where "if" is a statement). You could write code like this, which looks like multiple return statements (without explicitly using "return"):

*edit* Oh, I see I'm saying the same things as Matthew and Mike...
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8250
    
  23

Jesper de Jong wrote:In Scala, like in most functional programming languages, everything is an expression...

Yeah, I now dimly remember having seen something like it before; can't remember exactly where though. I have to admit to rather liking the style: Like I say, I dislike void methods in general, so most of mine tend to return something (or throw an exception). It's probably also why I dislike nulls so much.

Thanks a lot, anyway.

James Boswell wrote:Like we said earlier, everyone has their opinions about our craft.

Absolutely. And unless there's a major reason not do, doing what feels best is usually the way to go.
I look forward to hijacking future topics

Please do. It's been a fun discussion.

Winston
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Coding standards discussion - particularly multiple 'return's