Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2008

Tip: Looking for answers? Try searching our database.

return statement question (and a very newbie-ish one, too)

Thread view: 
Brian Munroe - 17 Apr 2008 16:51 GMT
Hello, I've got a return statement question.  Is the following best
practice for setting return values?  Is there a java (or any language
with try/catch) idiom for doing this?

thanks!

public class HelloWorld {

    public HelloWorld{};

    public int grabProcess(int processId) {

        int retValue;

        try {
            // do something
            ..

            retValue = 100;

        } catch (Exception e) {
            logger(e.printStackTrace());
            retValue = -100;
        }

        return retValue;
    }
}
Mark Space - 17 Apr 2008 17:02 GMT
>         } catch (Exception e) {
>             logger(e.printStackTrace());
>             retValue = -100;
>         }

I'd say no.

I assume what you are doing is setting retValue to indicate an error.
The "best practice" would be to throw an exception.  Checking the return
value has been shown to be brittle.  That's why exceptions were added to
languages like C++ and Java.

Propagate the exception (logging is a very good idea) or make a new
exception of the correct type for your method.

Also, you should not catch Exception, catch the specific type of
exception you really want. But I assume this is just an example.  I'm
going to change the type of Exception anyway, it really bugs me.

} catch ( SomeException e ) {
  logger( e.printStackTrace() );
  throw e;
}
Brian Munroe - 17 Apr 2008 17:21 GMT
> Also, you should not catch Exception, catch the specific type of
> exception you really want. But I assume this is just an example.  I'm
> going to change the type of Exception anyway, it really bugs me.

Yes, I know that catching a generic exception is considered bad form,
and yes, I just simplified things for the example.

I guess my question is, and granted I haven't tried it with the 'throw
e' - but where does the return statement go?  At the very bottom
(outer most scope) of the method?  I originally had it in the try{}
block, but the compiler complained.

thanks!
Mark Space - 17 Apr 2008 17:49 GMT
> I guess my question is, and granted I haven't tried it with the 'throw
> e' - but where does the return statement go?  At the very bottom
> (outer most scope) of the method?

I prefer at the very end.  Only if the logic of the method is very
simple is it ok to embed a return in the body of a method.  Or if
embedding the return simplifies the logic.

The reason here is just to make it simple to read.  The compiler is
allowed to rearrange things to make them more efficient.  Trust it to do
its job.

>  I originally had it in the try{}
> block, but the compiler complained.
>
> thanks!

Move it back to the try{} block.  Add the "throw e;" that I had in to
the catch{} block.  See if that helps.
Arved Sandstrom - 17 Apr 2008 18:25 GMT
>> Also, you should not catch Exception, catch the specific type of
>> exception you really want. But I assume this is just an example.  I'm
[quoted text clipped - 9 lines]
>
> thanks!

The compiler complained because there must be a reachable return. If you
stick your return in the try block and there's an exception beforehand you
won't have a return. There doesn't need to be a return statement in the
outermost scope, no, not if all the possible execution paths have a return
in them. Try an if-else and put returns in there, and not in the outermost
scope of the method - it will compile.

With try blocks, bear in mind that a return in a try won't, not if you have
a finally clause also. And don't use return in a finally clause...although
you can. Mind you, you'll get warned about the latter.

You can have (legally) a return in the try block, and the compiler won't
complain, not if there is no code prior that will throw an exception.

Having said all that, what's best practise, exceptions or not? Many people
will say that multiple return statements in a method are bad, others strive
for a single return statement (which under normal circumstances but not
always) would be in outermost method scope but occasionally use multiple
returns, and others sprinkle returns everywhere. I myself would sort of go
with Bruce Eckel here:
http://onthethought.blogspot.com/2004/12/multiple-return-statements.html

AHS
Brian Munroe - 21 Apr 2008 16:35 GMT
On Apr 17, 10:25 am, "Arved Sandstrom" <asandst...@accesswave.ca>
wrote:

> Having said all that, what's best practise, exceptions or not? Many people
> will say that multiple return statements in a method are bad, others strive
> for a single return statement (which under normal circumstances but not
> always) would be in outermost method scope but occasionally use multiple
> returns, and others sprinkle returns everywhere. I myself would sort of go
> with Bruce Eckel here:http://onthethought.blogspot.com/2004/12/multiple-return-statements.html

Thank you for a very concise answer regarding the compiler errors.  If
I would have thought about it more, I could have figured out what it
was saying, but thanks for affirming what I was already thinking.

Also, I've read the Bruce Eckel blog post, I think that makes sense
and I think I'll adopt it.
Chase Preuninger - 17 Apr 2008 21:20 GMT
looks good, I might just return the value right away and not set the
retValue varible because in your example it dosent matter but thats
just something I like to do.
thufir - 18 Apr 2008 19:15 GMT
>         try {
>             // do something
[quoted text clipped - 8 lines]
>
>         return retValue;

Why not use boolean?  true/false?

-Thufir
Roedy Green - 18 Apr 2008 20:11 GMT
On Thu, 17 Apr 2008 08:51:55 -0700 (PDT), Brian Munroe
<brian.e.munroe@gmail.com> wrote, quoted or indirectly quoted someone
who said :

>int retValue;

Wherever you can, use "final int retValue" to help someone reading
your code know you don't keep changing your mind even though it might
look superficially that you do.

In some cases, a multiple return results in easier-to-read code.
Purists frown at and pragmatists cheer the cheek.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Brian Munroe - 21 Apr 2008 16:38 GMT
On Apr 18, 12:11 pm, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:

> Wherever you can, use "final int retValue" to help someone reading
> your code know you don't keep changing your mind even though it might
> look superficially that you do.

Ok, good to know, thanks.

> In some cases, a multiple return results in easier-to-read code.
> Purists frown at and pragmatists cheer the cheek.

I should have figured I'd be asking a philosophical question :)
Andreas Leitgeb - 21 Apr 2008 17:14 GMT
>>int retValue;
> Wherever you can, use "final int retValue" to help someone reading
> your code know you don't keep changing your mind even though it might
> look superficially that you do.

Principially, I agree, but...

It's not uncommon to initialize such a variable with some value,
and eventually overwrite that under special conditions throughout
the method.

"Wherever you can", do it, but it's not a tragedy if you "cannot".


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.