Programming Languages – Benefits of Multiple Return Values

coding-styleprogramming-languages

I feel as if a return statement should only return one value. When it returns multiple, things get confusing. I know since the return type in Java has to be declared, this is difficult to do, but in languages like Python it is a snap.

Are multiple return values a sign of bad design or coding style?

Python example


def get_name():
   # you code
   return first_name, last_name

Best Answer

It's not a sign of anything, and is not neither good nor bad design or coding style.

Returning multiple values can actually be appropriate and allow to write less code. Let's take an example of a method which takes a string like "-123abc" and converts it to an integer like -123:

(bool, int) ParseInteger(string text)
{
    // Code goes here.
}

returns both:

  • a value indicating whether the operation was a success,
  • the number converted from string.

How can we refactor this?

1. Exceptions

We can add exceptions, if the language supports them. Remember than in most languages, exceptions are expensive in resources. It means that if you have to deal with lots of non-numbers, it's better to avoid to throw an exception every time the string cannot be converted to a number.

2. New class

We can create a class and return an instance of an object of this class.

For example:

class ParsedInteger
{
    bool IsSuccess { get; set; }
    int Number { get; set; }
}

Is it easier to understand? Shorter to write? Does it bring anything? I don't think so.

3. Out parameters

If the language supports it, we can also use out parameters. This is the approach of C# where returning multiple values is not possible. For example, when parsing a number, we use: bool isSuccess = int.TryParse("-123abc", out i). I'm not sure how is it better to use out parameters compared to multiple values. The syntax is not obvious, and even StyleCop itself (the tool used to enforce the default Microsoft style rules on the code) complains about those parameters, suggesting to remove them when possible.


Finally, in languages as C# where there is no such a thing as returning multiple values, things are progressively added to imitate the behavior. For example, Tuple was added to allow returning several values without having to write your own class or use out parameters.