Is Using .NET 4.0 Tuples in my C# Code a Poor Design Decision?
Asked Answered
S

13

173

With the addition of the Tuple class in .net 4, I have been trying to decide if using them in my design is a bad choice or not. The way I see it, a Tuple can be a shortcut to writing a result class (I am sure there are other uses too).

So this:

public class ResultType
{
    public string StringValue { get; set; }
    public int IntValue { get; set; }
}

public ResultType GetAClassedValue()
{
    //..Do Some Stuff
    ResultType result = new ResultType { StringValue = "A String", IntValue = 2 };
    return result;
}

Is equivalent to this:

public Tuple<string, int> GetATupledValue()
{
    //...Do Some stuff
    Tuple<string, int> result = new Tuple<string, int>("A String", 2);
    return result;
}

So setting aside the possibility that I am missing the point of Tuples, is the example with a Tuple a bad design choice? To me it seems like less clutter, but not as self documenting and clean. Meaning that with the type ResultType, it is very clear later on what each part of the class means but you have extra code to maintain. With the Tuple<string, int> you will need to look up and figure out what each Item represents, but you write and maintain less code.

Any experience you have had with this choice would be greatly appreciated.

Squaw answered 10/6, 2010 at 18:33 Comment(18)
Tuples are great if you like LISP!Castalia
I've never understood why we can't say "row" instead of "tuple". Why do we need a new word for this?Hight
@Boltbait: because tuple is from set theory en.wikipedia.org/wiki/TupleParlando
@BoltBait: A "tuple" is an ordered set of values, and doesn't necessarily have anything to do with rows in a database.Castalia
Tuples in c# would be even nicer if there was some good tuple unpacking action :)Springhalt
@Hight The way I see it is that when you have a row, you alse have a table and columns. But in the case of Tuple, you don't have that. They also aren't the same, because row's members have names.Calcariferous
My understanding is that Tuples are primarily intended for interoperability with dynamic languages. Within purely C# code, it's probably cleaner to use explicitly defined classes (when exposed publicly) or anonymous types.Threecornered
@Matthew - I suppose that's true. C# without { would be like lisp without ( :DAcree
@Jason: your question asks about tuples in .NET 4.0, yet the title asks about tuples in C#. Why is that? Tuples have nothing at all to do with C#. They are purely a .NET Framework thing.Dimer
@John Saunders My question is specifically about design decisions in c#. I don't use any other .net languages so I am unsure of how tuples impact them. So I marked it c#. It seemed reasonable to me but the change to .net is fine too I guess.Squaw
@FrustratedWithFormsDesigner: Lisp really does not have tuples, just lists. You cannot add an element to a tuple like you can a list and tuples also carry more type information. For instance I can have a tuple of (int, int, String) which is a different type than a list of strings and ints.Jagannath
@Jason: C# does not have tuples at all. There is no tuple support in the C# programming language. For instance, you can't do return (1,2);. It's important to understand the distinction between the .NET Framework and a .NET programming language like C# or VB.NET.Dimer
@John I do get that. What I am saying is I was looking for answers having to do specifically with c# and the use of the .net 4 Tuple class. The answer can be different in F# for instance since F# has better support for tuples. But it doesn't matter. Your edit to my title is fine. Good and helpful answers are coming in.Squaw
@Ukko: Hmm that's a good point, though the last time I worked with tuples (nested tuples, at that) - though it was with a Tuples class someone has written in Java (so maybe not quite the same as .NET) - I had a sudden LISP flashback. But I guess it's a more superficial similarity.Castalia
@Jason: I'm glad you're getting good answers, but what has me wondering is the fact that there are no design decisions in C# with respect to tuples, beyond the decision not to add language support for tuples.Dimer
@John Saunders: I am pretty sure he is asking about design decisions relating to using or not using Tuples in an application that is written purely in C#. I do not believe he is asking about design decisions that went into making the C# language.Abirritant
@Brett: if your interpretation is correct, then the title was worse than I thought.Dimer
#anotherHolyWar Food for thought : pedrorijo.com/blog/tuples-are-evil Why are tuples so bad? The bigger problems of using tuples: Usually, you can’t easily understand what each tuple field means without getting a lot of context. This probably includes trace back until the moment the tuple was created. Instead of using a tuple, had you chosen for a case class with proper names, it would be really straightforward to understand the meaning of each field. If you want to evolve the tuple to hold more info (meaning, adding a new value to the tuple), you break code (COMMENT LIMIT MET)Brammer
R
169

Tuples are great if you control both creating and using them - you can maintain context, which is essential to understanding them.

On a public API, however, they are less effective. The consumer (not you) has to either guess or look up documentation, especially for things like Tuple<int, int>.

I would use them for private/internal members, but use result classes for public/protected members.

This answer also has some info.

Rosa answered 10/6, 2010 at 18:49 Comment(4)
The difference between public/private is really important, thanks for bringing it up. Returning tuples in your public API is a really bad idea, but internally where things might be tightly coupled (but that's okay) it's fine.Wanitawanneeickel
Tightly coupled, or tightly tupled? ;)Headsman
Couldn't appropriate documentation be useful here? For example, Scala's StringOps (basically a class of "extension methods" for Java's String) has a method parition(Char => Boolean): (String, String) (takes in predicate, returns tuple of 2 strings). It's obvious what the output is (obviously one is going to be the characters for which the predicate was true and the other for which it was false, but it's not clear which is which). It's the documentation that clears this up (and pattern matching can be used to make it clear in usage which is which).Moulton
@Mike: That makes it hard to get right and easy to get wrong, the hallmark of an API that will cause pain for someone somewhere :-)Rosa
R
79

The way I see it, a Tuple is a shortcut to writing a result class (I am sure there are other uses too).

There are indeed other valuable uses for Tuple<> - most of them involve abstracting away the semantics of a particular group of types that share a similar structure, and treating them simply as ordered set of values. In all cases, a benefit of tuples is that they avoid cluttering your namespace with data-only classes that expose properties but not methods.

Here's an example of a reasonable use for Tuple<>:

var opponents = new Tuple<Player,Player>( playerBob, playerSam );

In the above example we want to represent a pair of opponents, a tuple is a convenient way of pairing these instances without having to create a new class. Here's another example:

var pokerHand = Tuple.Create( card1, card2, card3, card4, card5 );

A poker hand can be thought of as just a set of cards - and tuple (may be) a reasonable way of expressing that concept.

setting aside the possibility that I am missing the point of Tuples, is the example with a Tuple a bad design choice?

Returning strongly typed Tuple<> instances as part of a public API for a public type is rarely a good idea. As you yourself recognize, tuples requires the parties involved (library author, library user) to agree ahead of time on the purpose and interpretation of the tuple types being used. It's challenging enough to create APIs that are intuitive and clear, using Tuple<> publicly only obscures the intent and behavior of the API.

Anonymous types are also a kind of tuple - however, they are strongly typed and allow you to specify clear, informative names for the properties belonging to the type. But anonymous types are difficult to use across different methods - they were primarily added to support technologies like LINQ where projections would produce types to which we wouldn't normally want to assign names. (Yes, I know that anonymous types with the same types and named properties are consolidated by the compiler).

My rule of thumb is: if you will return it from your public interface - make it a named type.

My other rule of thumb for using tuples is: name method arguments and localc variables of type Tuple<> as clearly as possible - make the name represent the meaning of the relationships between elements of the tuple. Think of my var opponents = ... example.

Here's an example of a real-world case where I've used Tuple<> to avoid declaring a data-only type for use only within my own assembly. The situation involves the fact that when using generic dictionaries containing anonymous types, it's becomes difficult to use the TryGetValue() method to find items in the dictionary because the method requires an out parameter which cannot be named:

public static class DictionaryExt 
{
    // helper method that allows compiler to provide type inference
    // when attempting to locate optionally existent items in a dictionary
    public static Tuple<TValue,bool> Find<TKey,TValue>( 
        this IDictionary<TKey,TValue> dict, TKey keyToFind ) 
    {
        TValue foundValue = default(TValue);
        bool wasFound = dict.TryGetValue( keyToFind, out foundValue );
        return Tuple.Create( foundValue, wasFound );
    }
}

public class Program
{
    public static void Main()
    {
        var people = new[] { new { LastName = "Smith", FirstName = "Joe" },
                             new { LastName = "Sanders", FirstName = "Bob" } };

        var peopleDict = people.ToDictionary( d => d.LastName );

        // ??? foundItem <= what type would you put here?
        // peopleDict.TryGetValue( "Smith", out ??? );

        // so instead, we use our Find() extension:
        var result = peopleDict.Find( "Smith" );
        if( result.First )
        {
            Console.WriteLine( result.Second );
        }
    }
}

P.S. There is another (simpler) way of getting around the issues arising from anonymous types in dictionaries, and that is to use the var keyword to let the compiler 'infer' the type for you. Here's that version:

var foundItem = peopleDict.FirstOrDefault().Value;
if( peopleDict.TryGetValue( "Smith", out foundItem ) )
{
   // use foundItem...
}
Recapture answered 10/6, 2010 at 19:31 Comment(7)
Nice answer. But I think it would be more reasonable to use a Card[] array in your pokerHand example.Importune
@stakx: Yes, I agree. But keep in mind - the example is largely intended to illustrate cases when the use of a Tuple<> could make sense. There are always alternatives...Recapture
I think that replacing out parameters with a Tuple, as in TryGetValue or TryParse, is one of the few cases where it might make sense to have a public API return a Tuple. In fact, at least one .NET language automatically makes this API change for you.Purism
@stakx: Tuples are also immutable, whereas arrays are not.Signboard
I understood that Tuples are useful only as immutable poker player objects.Finbur
+1 Great answer - I love your two initial examples which actually changed my mind slightly. I never saw examples before where a tuple was at least as much appropriate as a custom struct or type. However, your last "real life example" to me seems not to add much value any more. The first two examples are perfect and simple. The last is a bit hard to understand and your "P.S." kind of renders it useless since your alternate approach is much simpler and does not require tuples.Radom
Was trying to understand your example but using .NET 4/4.5 I can't get it to compile. It complains that result.First and result.Second are not members of Tuple. Did you mean Item1, Item2 perhaps?Specialistic
P
20

Tuples can be useful... but they can also be a pain later. If you have a method that returns Tuple<int,string,string,int> how do you know what those values are later. Were they ID, FirstName, LastName, Age or were they UnitNumber, Street, City, ZipCode.

Parlando answered 10/6, 2010 at 18:48 Comment(0)
G
9

Tuples are pretty underwhelming addition to the CLR from the perspective of a C# programmer. If you have a collection of items that varies in length, you don't need them to have unique static names at compile time.

But if you have a collection of constant length, this implies that the fixed of locations in the collection each have a specific pre-defined meaning. And it is always better to give them appropriate static names in that case, rather than having to remember the significance of Item1, Item2, etc.

Anonymous classes in C# already provide a superb solution to the most common private use of tuples, and they give meaningful names to the items, so they are actually superior in that sense. The only problem is that they can't leak out of named methods. I'd prefer to see that restriction lifted (perhaps only for private methods) than have specific support for tuples in C#:

private var GetDesserts()
{
    return _icecreams.Select(
        i => new { icecream = i, topping = new Topping(i) }
    );
}

public void Eat()
{
    foreach (var dessert in GetDesserts())
    {
        dessert.icecream.AddTopping(dessert.topping);
        dessert.Eat();
    }
}
Garment answered 11/6, 2010 at 15:8 Comment(9)
As a general feature, what I'd like to see would be for .net to define a standard for a few special kinds of anonymous types, such that e.g. struct var SimpleStruct {int x, int y;} would define a struct with a name that starts with a guid associated with simple structs and has something like {System.Int16 x}{System.Int16 y} appended; any name starting with that GUID would be required to represent a struct containing just those elements and particular specified contents; if multiple definitions for the same name are in scope and they match, all would be considered the same type.Furriery
Such a thing would be helpful for a few kinds of types, including mutable and immutable class- and struct- tuples as well as interfaces and delegates for use in situations where matching structure should be deemed to imply matching semantics. While there are certainly reasons why it's may be useful to have two delegate types that have the same parameters not be considered interchangeable, it would also be helpful if one could specify that a method wants a delegate that takes some combination of parameters but beyond that doesn't care what kind of delegate it is.Furriery
It's unfortunate that if two different people want to write functions that take as input delegates which need a single ref parameter, the only way it will be possible to have one delegate that can be passed to both functions will be if the one person produces and compiles a delegate type and gives it to the other to build against. There's no way both people can indicate that the two types should be considered synonymous.Furriery
Do you have any more concrete examples of where you'd use anonymous classes rather than Tuple? I just skimmed through 50 places in my codebase where I'm using tuples, and all are either return values (typically yield return) or are elements of collections which are used elsewhere, so no go for anonymous classes.Stefan
@JonofAllTrades - the consuming code of those collections/enumerables therefore have references to Item1, Item2, etc. scattered around them. Wouldn't they be more readable if they referred to meaningful names?Garment
@DanielEarwicker: Absolutely, which is why I'd like to refactor them. However, since I can't return an anonymous class, or declare (for example) a Dictionary<> with an anonymous class for the key, I don't think they're an option for any of these instances. I could write and use little structs, but not anonymous classes.Stefan
@JonofAllTrades - yes, little classes. Anonymous classes are sadly of no use in public APIs (half my above answer was pleading for a new language feature, for exactly that reason!) They are occasionally useful in complex Linq expressions (although there you can typically use let to achieve the same thing in a more readable way).Garment
@DanielEarwicker: Gotcha, so people's references here to "public APIs" uses "public" broadly, meaning about any time you expose information outside of a method (as I am for most of these 50 cases). I had interpreted it as meaning "don't use tuples for a published API which will be used by other developers", but I see that this is too narrow. Thank you for the clarification!Stefan
@JonofAllTrades - opinions probably vary on that, but I try to design the public methods as if they were going to be used by someone else, even if that someone is me, so I'm giving myself good customer service! You tend to call a function more times than you write it. :)Garment
A
8

Similar to keyword var, it is intended as a convenience - but is as easily abused.

In my most humble opinion, do not expose Tuple as a return class. Use it privately, if a service or component's data structure requires it, but return well-formed well-known classes from public methods.

// one possible use of tuple within a private context. would never
// return an opaque non-descript instance as a result, but useful
// when scope is known [ie private] and implementation intimacy is
// expected
public class WorkflowHost
{
    // a map of uri's to a workflow service definition 
    // and workflow service instance. By convention, first
    // element of tuple is definition, second element is
    // instance
    private Dictionary<Uri, Tuple<WorkflowService, WorkflowServiceHost>> _map = 
        new Dictionary<Uri, Tuple<WorkflowService, WorkflowServiceHost>> ();
}
Aranyaka answered 10/6, 2010 at 18:49 Comment(6)
Mainstream "RAD" languages (Java is the best example) have always chosen safety and avoiding shooting yourself in the foot type scenarios. I am glad Microsoft is taking some chances with C# and giving the language some nice power, even if it can be misused.Beachhead
The var keyword is not possible to abuse. Perhaps you meant dynamic?Ader
@Chris Marisic, just to clarify i did not mean in the same scenario - you are absolutely correct, var cannot be passed back or exist outside of its declared scope. however, it is still possible to use it in excess of its intended purpose and be "abused"Aranyaka
@Chris Marisic, also, did not mean to single out var. indeed, any feature can be "abused" to obtain a "desired" result.Aranyaka
I still stand on that var cannot be abused period. It is merely a keyword to make a shorter variable definition. Your argument perhaps is about anonymous types but even those really can't be abused because they're still normal statically linked types now dynamic is quite a different story.Ader
var can be abused in the sense that if it is overused it can sometimes cause issues for the person reading the code. Especially if you're not in Visual Studio and lack intellisense.Beachhead
H
5

Using a class like ResultType is clearer. You can give meaningful names to the fields in the class (whereas with a tuple they would be called Item1 and Item2). This is even more important if the types of the two fields are the same: the name clearly distinguishes between them.

Hickman answered 10/6, 2010 at 18:47 Comment(2)
One small additional advantage: you can safely reorder the parameters for a class. Doing so for a tuple will break code, and if the fields have similar types this may not be detectable at compile time.Stefan
I agree, Tuples are used when a developer lacks the energy to think of a meaningful class name grouping meaningful property names. Programming is about communication. Tuples are an antipattern to communication. I would have preferred Microsoft left it out of the language to force developers to make good design decisions.Gravel
W
5

How about using Tuples in a decorate-sort-undecorate pattern? (Schwartzian Transform for the Perl people). Here's a contrived example, to be sure, but Tuples seem to be a good way to handle this kind of thing:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = Directory.GetFiles("C:\\Windows")
                    .Select(x => new Tuple<string, string>(x, FirstLine(x)))
                    .OrderBy(x => x.Item2)
                    .Select(x => x.Item1).ToArray();
        }
        static string FirstLine(string path)
        {
            using (TextReader tr = new StreamReader(
                        File.Open(path, FileMode.Open)))
            {
                return tr.ReadLine();
            }
        }
    }
}

Now, I could have used an Object[] of two elements or in this specific example a string [] of two elements. The point being that I could have used anything as the second element in a Tuple that's used internally and is pretty easy to read.

Wanitawanneeickel answered 11/6, 2010 at 14:42 Comment(3)
You can use Tuple.Create instead of constructor. It's shorter.Ias
an anonymous type will be much more readable; as would using real variable names instead of 'x'Forfeit
It would now. That's a SO problem, answers posted years and years ago never get cleaned up or updated for new technology.Wanitawanneeickel
P
4

IMO these "tuples" are basically all public access anonymous struct types with unnamed members.

The only place I would use tuple is when you need to quickly blob together some data, in a very limited scope. The semantics of the data should be are obvious, so the code is not hard to read. So using a tuple (int,int) for (row,col) seems reasonable. But I'm hard pressed to find an advantage over a struct with named members (so no mistakes are made and row/column aren't accidentally interchanged)

If you're sending data back to the caller, or accepting data from a caller, you really should be using a struct with named members.

Take a simple example:

struct Color{ float r,g,b,a ; }
public void setColor( Color color )
{
}

The tuple version

public void setColor( Tuple<float,float,float,float> color )
{
  // why?
}

I don't see any advantage to using tuple in the place of a struct with named members. Using unnamed members is a step backward for the readability and understandability of your code.

Tuple strikes me as a lazy way to avoid creating a struct with actual named members. Overuse of tuple, where you really feel you/or someone else encountering your code would need named members is A Bad Thing™ if I ever saw one.

Phuongphycology answered 10/5, 2013 at 21:37 Comment(0)
L
3

Don't judge me, I'm not an expert, but with new Tuples in C# 7.x now, you could return something like:

return (string Name1, int Name2)

At least now you can name it and developers might see some information.

Luehrmann answered 9/3, 2018 at 19:0 Comment(1)
This does not answer the questionApprehensive
J
2

It depends, of course! As you said, a tuple can save you code and time when you want to group some items together for local consumption. You can also use them to create more generic processing algorithms than you can if you pass a concrete class around. I can't remember how many times I've wished I had something beyond KeyValuePair or a DataRow to quickly pass some date from one method to another.

On the other hand, it is quite possible to overdo it and pass around tuples where you can only guess what they contain. If you are going to use a tuple across classes, perhaps it would be better to create one concrete class.

Used in moderation of course, tuples can lead to more concise and readable code. You can look to C++, STL and Boost for examples of how Tuples are used in other languages but in the end, we will all have to experiment to find how they best fit in the .NET environment.

Jemadar answered 10/6, 2010 at 18:49 Comment(0)
A
1

Tuples are a useless framework feature in .NET 4. I think a great opportunity was missed with C# 4.0. I would have loved to have tuples with named members, so you could access the various fields of a tuple by name instead of Value1, Value2, etc...

It would have required a language (syntax) change, but it would have been very useful.

Astred answered 10/6, 2010 at 20:12 Comment(9)
How are tuples a "language feature"? Its a class available to all .net languages isn't it?Squaw
Relatively useless to C#, perhaps. But System.Tuple wasn't added to the framework because of C#. It was added to ease interoperability between F# and other languages.Purism
@Jason: I didn't say it was a language feature (I did mistype that, but I corrected it before you made this comment).Astred
@Jason - languages with direct support for tuples have implicit support for deconstructing tuples into their component values. Code written in those languages typically never, ever, accesses the Item1, Item2 properties. let success, value = MethodThatReturnsATuple()Purism
@Joel: this question is tagged as C#, so it's somehow about C#. I still think they could have turned it into a first-class feature in the language.Astred
@Philippe Leybaert That makes more sense. I retract my earlier comment. I must have been looking at a cached version of the page before your edit.Squaw
@Joel Mueller It was about c# specifically. John Saunders edited the title.Squaw
@Philippe - I agree, having first-class support for tuples in C# would be very convenient. But the fact remains that tuples are not useless, even to C#. Without System.Tuple, C# code that called into an F# library that returns a tuple from a method would have had to add a reference to FSharp.Core.dll. Because tuples are part of the framework instead of part of F#, it makes interoperability easier.Purism
FWIW, C# 7.0 tuples will support named members.Sentient
M
1

I would personally never use a Tuple as a return type because there is no indication of what the values represent. Tuples have some valuable uses because unlike objects they are value types and thus understand equality. Because of this I will use them as dictionary keys if I need a multipart key or as a key for a GroupBy clause if I want to group by multiple variables and don't want nested groupings (Who ever wants nested groupings?). To overcome the issue with extreme verbosity you can create them with a helper method. Keep in mind if you are frequently accessing members (through Item1, Item2, etc) then you should probably use a different construct such as a struct or an anonymous class.

Magnetoelectricity answered 9/10, 2014 at 16:11 Comment(0)
K
0

I've used tuples, both the Tuple and the new ValueTuple, in a number of different scenarios and arrived at the following conclusion: do not use.

Every time, I encountered the following issues:

  • code became unreadable due to lack of strong naming;
  • unable to use class hierarchy features, such as base class DTO and child class DTOs, etc.;
  • if they are used in more than one place, you end up copying and pasting these ugly definitions, instead of a clean class name.

My opinion is tuples are a detriment, not a feature, of C#.

I have somewhat similar, but a lot less harsh, criticism of Func<> and Action<>. Those are useful in many situations, especially the simple Action and Func<type> variants, but anything beyond that, I've found that creating a delegate type is more elegant, readable, maintainable, and gives you more features, like ref/out parameters.

Knothole answered 1/6, 2018 at 0:39 Comment(2)
I mentioned named tuples - ValueTuple - and I don't like them, either. First, the naming isn't strong, it's more of a suggestion, very easy to mess up because it can be assigned implicitly to either Tuple or ValueTuple with the same number and types of items. Second, the lack of inheritance and the need to copy paste the whole definition from place to place are still detriments.Knothole
I agree with those points. I try to only use Tuples when I control the producer and consumer, and if they aren't too "far away". Meaning, producer and consumer in the same method = 'close', whereas producer and consumer in different assemblies = 'light years away'. So, if I create tuples in the beginning of a method, and use them at the end? Sure, I'm okay with that. I also document the terms and such. But yeah, I agree that generally they're not the right choice.Manque

© 2022 - 2024 — McMap. All rights reserved.