Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most inuitive way to ask for objects in pairs?

Tags:

c#

usability

So I have to design a class that works on a collection of paired objects. There is a one-to-one mapping between objects. I expect the client of the class to have established this mapping before using my class.

My question is what is the best way to allow the user of my class to give me that information?

Is it to ask for a collection of pairs like this?

MyClass(IEnumerable<KeyValuePair<Object, Object>> objects)

Or seperate collections like this?

MyClass(IEnumberable<Object> x, IEnumerable<Object> y)

Or is there another option?

I like the first because the relationship is explicit, I don't like it because of the extra work it puts on the client.

I like the second because the types are more primitive and require less work, I don't like it because the mapping is not explicit. I have to assume the order is correct.

Opinions please?

like image 880
Neil Anderson Avatar asked Jul 12 '10 19:07

Neil Anderson


3 Answers

In .NET 4 you should be using Tuple<T1,T2>. More info on the Tuple class at MSDN.

like image 179
tvanfosson Avatar answered Oct 22 '22 09:10

tvanfosson


If you have access to it, use Tuple<T, R>. If you don't, just write a generic Tuple or Pair class of your own. I would avoid using KeyValuePair, just because it's verbose and has an association with Dictionary.

like image 38
JSBձոգչ Avatar answered Oct 22 '22 08:10

JSBձոգչ


I would prefer KeyValuePair of the two you mention as it's more expressive and keeps the relationship between the objects.

But I would rather create a class which holds a reference to your pair. This is more readable in my opinion, and it never hurts to create an extra class or struct to express your actual actions.

(Pseudo-code)

class MyPair
{
    public TypeA One;
    public TypeB Two;
}

MyClass(IEnumerable<MyPair> objects)

There's mention of Tuple<,> in some answers, which is as readable as KeyValuePair, but more flexible as it can contain more than two parameters.

[Edit - more indepth about Tuples/classes after a good nights sleep]

To Tuple or Not To Tuple

like image 31
Mikael Svenson Avatar answered Oct 22 '22 07:10

Mikael Svenson