Why use tuples instead of objects?

后端 未结 10 1978
别那么骄傲
别那么骄傲 2020-12-24 05:29

The codebase where I work has an object called Pair where A and B are the types of the first and second values in the Pair. I find this object to be offensive, because it g

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 05:49

    The code example has a few different smells:

    • Reinventing the wheel

    There is already a tuple available in the framework; the KeyValuePair structure. This is used by the Dictionary class to store pairs, but you can use it anywhere it fits. (Not saying that it fits in this case...)

    • Making a square wheel

    If you have a list of pairs it's better to use the KeyValuePair structure than a class with the same purpose, as it results in less memory allocations.

    • Hiding the intention

    A class with properties clearly shows what the values mean, while a Pair class doesn't tell you anything about what the values represent (only that they are probably related somehow). To make the code reasonably self explanatory with a list like that you would have to give the list a very desciptive name, like productIdAndQuantityPairs...

提交回复
热议问题