I like the concept of System.Tuple in that it allows me to return multiple parameters in a single function call without instantiating a new class, however does this defy any good programming practices such as Microsoft Patterns & Practices, SOLID Principles, etc.

I'm just trying to gauge how liberally I should use this feature or if I should only use it in edge case scenarios when necessary.

  • +1: Excellent question. Also - I wonder if Anders Hejlsberg has weighed in on this. – Jim G. Dec 8 '11 at 20:06

The issue with using Tuple is that the generic type parameters do not convey meaning.

For readability you may want to consider using a custom class or even an anonymous type with named members.

  • What about the XML parameter description? Not the most obvious place to look, but better than nothing. – John Bubriski Dec 8 '11 at 20:36
  • @SkippyFire - How do you mean? All you get is the type of T1, T2 etc. Doesn't tell you what they mean. – Oded Dec 8 '11 at 21:00
  • 2
    I have to say: every time I (or someone on our team) has used a Tuple as a type, I am constantly referring back to other parts in the code to remember what .Item1, .Item2, etc. are. For anything that is not completely trivial, create discrete classes. Give yourself a chance in the future to know what it is you were doing. – Joe Dec 9 '11 at 1:29
  • @Oded I'm talking about adding XML documentation to a method accepting a Tuple. Again, not perfect, but better than nothing if you want/need to use Tuples. – John Bubriski Mar 8 '12 at 18:00
  • 1
    @Oded Also, the parameter or return value may not convey meaning, but the name of the method can. Let's say you have a method called GetTopTwoPercentages() that returns a Tuple<decimal, decimal>. That might be clear enough. – John Bubriski Mar 8 '12 at 18:02

One of the most important code qualities is readability. So ask yourself:
When I (i.e. in anybody else but you) look at the method signature, do I know what meaning the respective components of the Tuple have?
For example if the pair of floats you are returning is a set of polar coordinates, is this clear?

This is clear:

Tuple<Float, Float> getPolarCoords();

This is misleading (because one would assume Cartesian coordinates):

Tuple<Float, Float> getCoords();

And this is devoid meaning:

Tuple<Float, Float> getTuple();

So generally speaking, you will have evaluate clarity on a per-case basis and refactor if necessary. If you represent the same kind of data as Tuple in many different places, then creating a class is definitely a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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