views:

155

answers:

3

What’s the best practice when returning something from a routine? Should I return a status bit always or just on failure? For example:

Return(0, “Failed because….”) on failure,
Return(1, success_value, second_success_value) on success.

Or

Return(0, “Failed because….”) on failure,
Return( success_value, second_success_value) on success.

I usually program in Perl, but I guess the question stands for whatever language I might try to program in. Thanks!

+1  A: 

In languages that support them, you should throw descriptive exceptions.

Where applicable, you should throw exceptions of the correct type (eg, ArgumentNullException or InvalidOperationException in .Net)

SLaks
A: 

hey Akers, I've asked myself a similar question in the past...

Some of these answers might help you

http://stackoverflow.com/questions/973292/is-it-bad-practice-to-return-exceptions-from-your-methods

The basic conclusion I came to is to only return something, anything, if the caller requires it.

So, for the most part, I found its better to just make my method Void, and have it throw a meaningful exception if anything goes wrong. If everything goes ok, then I, as the caller, don't really care

andy
+3  A: 

The answer is very language dependent. You should follow the idiom for the language you are using. The idiom for Perl, which you mentioned, is to return zero(0) for success and other values for failure. If you need to return multiple values, as in your example, one of them could always be the success/failure code.

If you're using a language that supports exceptions (eg. Java, C#, C++) then you should indicate exceptional conditions (eg. failures) using an exception. If the routine completes normally (ie. no exceptions) then it can be assumed to have succeeded and any returned values can be used safely.

dave
@dave could I ask where you got the Perl idiom to return 0 as succes. Because it seems like I've seen Perl code in the past that returns 1 for success. I like to try to use best practice when I know it, and will change the habit if what you suggest is true.
Akers
I think this is embedded in my DNA now :) I can't think of a reference off hand, but I'm pretty sure it reflects Perl's Unix heritage. Can I suggest google.There's also the idea that there's only one form of success and many forms of failure. So picking 0 for success and non-zero for all the possible failures kind of makes sense.
dave
Perl Cookbook says you should return undef / empty list on failure and just return; without arguments should do that. http://raca.teroristi.org/books/perl/OReilly_books/cookbook/ch10_11.htm
Marie Fischer