Coffeehouse Post

Single Post Permalink

View Thread: How are you using Tuple in code?
  • User profile image

    , Dr Herbie wrote

    Because I'm in the office a little early and there's no one else to distract me, I've been analysing my coding style.

    I have decided that the Tuple<> class is ugly (having to remember which type is 'Item1' and which is 'Item2') and that it should only be used within a class and never used as a result passed out of a public class method or property; I think it's OK to use within a class's private methods, but it's a bit of a 'sausage factory' argument.

    So do you use Tuple<> at all?


    Not that much. Tuples can be used to model fixed-length, statically-typed, heterogeneous collections. If the tuple is large it becomes hostile to use in my oppinion: like a long function parameter list; this is, I believe, the reason why named arguments were introduced in C#.

    In F# they look syntactically nicer but F# also has immutable record types which in my oppinion are much, much better since they are self-documenting - unlike tuples. Tuples are kind of everywhere anyway though, as argument lists and also in discriminated union constructors.

    For simple things like coordinate sets tuples can be fine (although one wonders what their performance will be with Tuple being implemented as a reference type).

    One place where I could maybe see using a tuple could be e.g. a list search function which returns both the index of an element as well as the element itself. However, given a choice, the record type would almost always be better, in my oppinion. Also, come to think of it if the element type is the same as the index type it is confusing again, without resorting to the documentation. Record types eliminate all confusion.

    The question is whether the syntactic overhead of the object literal makes the code harder to easier to read. If a tuple is used locally in a function for some purpose but is not passed around then it can also be appropriate but then again, one could also just use two or more local variables for that. The more I think of them, the less I like tuples. They are often ambiguous constructs.