Tuple<> to class/struct feature
Some people tend to use Tuples extensively. This in my opinion is making the code harder to understand since one looses the semantics of the content in the tuple. Let's say I want to store the name and length of a person. If I do this using a tuple I end up with Tuple<string, float>. This might be obvious where created, at least if the variable is named personNameAndLength. Unfortunatelly this is rarely the case. This tuple is typically passed to some other method and named personInfo. Now what does personInfo.Item2 represent? I Know it's a float but what is its semantics. In my opinon this is bad code. A better way would be to actually create a class (or struct) with the properties/fields named Name and Length. However, people are lazy and tend to take the easiest path forward.
To solve this I suggest a Tuple<T1, T2, ...> to class/struct converter.
The user should be prompted to specify:
1. class/struct with name
2. field/properties
3. name of fields
For the specific usage of a tuple, lets say.
var personNameAndLength = registry.GetPersonInfo("..."); // Returns Tuple<string, float>
...
something.DoStuffWIthPerson(personNameAndLength);
the signature of DoStuffWIthPerson should obviously be updated with the name of the new type and the usage trail of that specific Tuple should be followed throughout the entire code base.
Please sign in to leave a comment.
First of all, no one should use Tuples extensively in C#. It is a bad practice. Tuples are great for prototyping objects that will become classes or structs, but where you don't know how many fields will be required until you finish your logic. However, they make for a terrible final output. What you want to use is a POCO in C#.
The addition of Tuple was most likely added for IronPython, back when Microsoft was adding dynamic language support and needed to handle tuples and multiple-valve returns for languages like Python. Python, being dynamic, don't require the overhead (type safety) that we use in C#.
I'm onboard with adding a Tuple conversion mechanism, to a POCO (class or struct).
Example:
Tuple<string, string, int> groupMembers
Becomes:
class GroupMembers
{
public string NameMe1 { get; set; }
public string NameMe2 { get; set; }
public int NameMe3 { get; set; }
}
...where things in Pink are editable.
For reference, in Python this would just be:
groupMembers = (NameMe1, NameMe2, NameMe3)
Since I believe Tuples are a bad practice in C#, I wouldn't want to add anything to make it easier to use Tuples, but rather something that would make it easier to un-use Tuples--as in classes/structs.