File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes End a method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "End a method" Watch "End a method" New topic
Author

End a method

Nicholas Carrier
Ranch Hand

Joined: Apr 14, 2005
Posts: 78
Here's the question: Is there a way to get to the end of a method and skip everything like break in a loop.

For example

public String getAnswer() {
String answer = null;

If (something == somethingElse) {
answer = "Yo' Momma";
// what would go here to go straight to the return
}

// other stuff which would lead to a different answer
answer = "Yo' Sister"

return answer;

}


Is there no other way than using else? Basically, how do I stop a method from finishing and go straight to a return?


Teaching yourself anything is always the cheapest way, but it definitely takes a lot of time and effort.<br /> <br />Thank you javaranch <a href="http://"http://faq.javaranch.com/view?HowToAskQuestionsOnJavaRanch"" target="_blank" rel="nofollow">Learn How to Ask Your Question</a> and be nice
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Nicholas Carrier:
... Basically, how do I stop a method from finishing and go straight to a return?

By inserting another return...


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Nicholas]: Basically, how do I stop a method from finishing and go straight to a return?

In fact, there is a statement that does exactly this. It's called... wait for it... a return statement. You can actually invoke return from anywhere in a method - assuming you don't accidentally make it totally impossible for the subsequent code to ever be executed, in which case the compiler will complain that you've got some unreachable code. Typically though you can easily put a return in an if clause, in which case subsequent code is accessible from the "else".

Using your example code, you could write:

Though in this case you could also eliminate the else, and write (equivalently)

or better yet

which goes back to avoiding the original question entirely. But hopefully the earlier examples answered it well enough.

Note that you may well encounter some people who feel that a return anywhere other than the end of a method is wrong as it makes code "hard to read". These same people generally say the same thing about break (other than in a switch) and continue. I am tempted to say you should ignore these people. But instead, I recommend you react by making a point of inserting as many returns, breaks, and continues as possible in your code, just to annoy those people. That's what I do, anyway.

No, seriously, I think you should consider whether there's a way to avoid the multiple returns and produce something that is more readable. (Which I feel I achieved above with the last code example, but that's a matter of opinion.) I think multiple returns are something you should be careful not to overuse, particularly in long methods. But sometimes, multiple returns may really be the best solution. (Same with continue and break.) But be prepared to change it to something more convoluted if your boss is intolerant of such things. I would also note that long methods are inherently evil, and if code is unreadable because it's hard to spot the multiple returns in your really long method, the problem isn't the multiple returns, it's the really long method. Break it up into several shorter methods first, and that will generally fix any other readability problem.

The previous two paragraphs are my own opinions, which some other people will doubtless disagree with. Be aware that whichever side you choose here, there will be other people who disagree; oh well. But as a technical matter, it's entirely possible to call return from the middle of a method.
[ November 02, 2006: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Nicholas Carrier
Ranch Hand

Joined: Apr 14, 2005
Posts: 78
I was actually coming here to delete the question

As always, thanks for the help and I'm going to try use a way to make it more readable as suggested.

<----feels dumb
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The discussion about multiple returns was worth having, so I'm glad you didn't delete the question.

Opinion: A method small enough that you can totally grok it in a glance is ok with a couple returns. A method that requires you to move your eyes up and down to read it can certainly get into trouble with multiple returns.

About half related to this topic ... you could look for ways to eliminate the if-else chain. Maybe ...

or make "something" an object with polymorphic behavior instead of just a String ...

Note how you can add new relationships and smart answers without touching this code. Does that sound like fun?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18101
    
  39

Note that you may well encounter some people who feel that a return anywhere other than the end of a method is wrong as it makes code "hard to read". These same people generally say the same thing about break (other than in a switch) and continue. I am tempted to say you should ignore these people. But instead, I recommend you react by making a point of inserting as many returns, breaks, and continues as possible in your code, just to annoy those people. That's what I do, anyway.


I am also one of those who uses multiple returns. But then again, my methods are generally small and highly documented. In many cases, the comments are longer than the code... I don't insert more returns to annoy "those people", but I do it for the ternary operator.

How could anyone not like the ternary operator? I actually enjoy annoying "those people". And have gotten really good at using them. Heck, once I wrote a method that was about a page long, with only a single return expression. (one big wad of ternary operators with ternary operators)

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Stan James:
The discussion about multiple returns was worth having, so I'm glad you didn't delete the question...

I agree. I also wouldn't feel "dumb" about asking this, because I think it's a reasonable question -- especially if you were in the mindframe of looking for a "goto" type solution.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Stan]: Opinion: A method small enough that you can totally grok it in a glance is ok with a couple returns. A method that requires you to move your eyes up and down to read it can certainly get into trouble with multiple returns.

Agreed. I'm also more tolerant of extra returns very near the beginning of a method, e.g.

That's assuming I wouldn't prefer to throw some sort of exception at the beginning, which is often what I'd do instead. But, you know, depending on the circumstances...

[Henry]: How could anyone not like the ternary operator?

Agreed. Though I'm much less happy with nested ternaries. Unless you've got some trick for formatting them that makes it really clear to everyone what's going on. I will sometimes put together a few consecutive ternaries, equivalent to a series of if / else if / else if / else statements. Most commonly in a Comparator:

[ November 03, 2006: Message edited by: Jim Yingst ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I never would have made that up, but I might steal it.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
OK, no problem. Just please include the following copyright statement in the code:

[ November 03, 2006: Message edited by: Jim Yingst ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: End a method
 
Similar Threads
Thread self test SCJP6
setting a return of one method from another method?
Difference between GET and POST
K&B chapter 9 Threads question 15
Thread synchronization problem K&B, SCJP 6 - chapter 9, question 15