Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

language agnostic - How do you return two values from a single method?

When your in a situation where you need to return two things in a single method, what is the best approach?

I understand the philosophy that a method should do one thing only, but say you have a method that runs a database select and you need to pull two columns. I'm assuming you only want to traverse through the database result set once, but you want to return two columns worth of data.

The options I have come up with:

  1. Use global variables to hold returns. I personally try and avoid globals where I can.
  2. Pass in two empty variables as parameters then assign the variables inside the method, which now is a void. I don't like the idea of methods that have a side effects.
  3. Return a collection that contains two variables. This can lead to confusing code.
  4. Build a container class to hold the double return. This is more self-documenting then a collection containing other collections, but it seems like it might be confusing to create a class just for the purpose of a return.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not entirely language-agnostic: in Lisp, you can actually return any number of values from a function, including (but not limited to) none, one, two, ...

(defun returns-two-values ()
  (values 1 2))

The same thing holds for Scheme and Dylan. In Python, I would actually use a tuple containing 2 values like

def returns_two_values():
   return (1, 2)

As others have pointed out, you can return multiple values using the out parameters in C#. In C++, you would use references.

void 
returns_two_values(int& v1, int& v2)
{
    v1 = 1; v2 = 2;
}

In C, your method would take pointers to locations, where your function should store the result values.

void 
returns_two_values(int* v1, int* v2)
{
    *v1 = 1; *v2 = 2;
}

For Java, I usually use either a dedicated class, or a pretty generic little helper (currently, there are two in my private "commons" library: Pair<F,S> and Triple<F,S,T>, both nothing more than simple immutable containers for 2 resp. 3 values)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...