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

不打扰是莪最后的温柔 提交于 2019-11-27 10:12:59
Bryan Watts

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.

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...
}

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.

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();
    }
}

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>> ();
}

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.

Clinton Pierce

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.

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.

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.

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.

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!