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

前端 未结 13 1855
我在风中等你
我在风中等你 2020-12-02 04:55

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

13条回答
  •  遥遥无期
    2020-12-02 05:42

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

提交回复
热议问题