2

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!

3 Answers 3

3

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.

3
  • @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
    Jul 9, 2009 at 1:50
  • 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
    Jul 9, 2009 at 1:59
  • Perl Cookbook says you should return undef / empty list on failure and just return; without arguments should do that. raca.teroristi.org/books/perl/OReilly_books/cookbook/… Jul 9, 2009 at 2:27
1

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)

0

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

Some of these answers might help you

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.