This will spark quite a debate (I hope)! Continuing on the code smell subject I actually would like to challenge some opinions in regards to Tuple, Anonymous Type and out parameters in C#. These three have in common that they allow you to return multiple values from a function, but in three different ways. When I asked the Tuple question many argued that Anonymous Types would be better since they let you set meaningful names on the ‘properties’, while many argued that Tuple was a blessing since they could replace out parameters. I kind of don’t like using any of them, although I have to admit that I have been using Anonymous types, for private functions within a class mainly- why? I don’t know – it felt right as long as I kept them in the sandbox. But I want to know, are these considered code smells?
I’ve spent three days asking other developers and searching the internet for a good answer, and it probably doesn’t come as a surprise if I say that it depends? The majority of the senior developers I have asked have answered that:
– Out in TryParse is okay, but use it only when needed. Extensive use might indicate that the method is doing too much,- and therefore violating the single responsibility principle.
– Out is often overused, and has only a few specific scenarios were it has value
– Tuple seemed to be the least popular one, as it didn’t allow meaningful names (not semantic) and is bulky once you get beyond 8 elements
– Anonymous types are similar to Tuples but allow you to set descriptive names, and they do seem to be more accepted than extensive use of out parameters or Tuples.
– In short- the impression I got was that in most cases (99% as one developer put it) none of the above alternatives should be used since methods should be kept small and have a single responsibility (“Why would you want to return several values?”) – And it COULD indicate a lazy programmer, or an inexperienced one.
– Some suggested that it could be okay, if the they are used in private functions, and some developers did not see any problem in using them at all (“Creating a class seems overkill if you aren’t going to use it in several places”).
My conclusion: I’ll probably think through more before I use anonymous types, I haven’t used out much and haven’t used Tuples at all,- and I don’t see a reason to introduce them in my code right now. As for making a general statement about code smell – I think they MIGHT indicate a code smell and I am skeptical to use any of them, at least extensively. But, I would love to hear some more opinions on this,- and I know that you have one!
Thank you again for all of you that take a part in my daily questions, on the blog, twitter or work/private. I learn so much more from these talks and comments that I would ever be able to learn from books or courses. Please share comments here so others can learn too! Share your wisdom 😀