Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use tuples instead of objects?

Tags:

c++

tuples

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 gets used instead of an object with clearly named members. So I find this:

List<Pair<Integer, Integer>> productIds = blah(); // snip many lines and method calls  void doSomething(Pair<Integer, Integer> id) {   Integer productId = id.first();   Integer quantity = id.second(); } 

Instead of

class ProductsOrdered {   int productId;   int quantityOrdered;   // accessor methods, etc }  List<ProductsOrderded> productsOrdered = blah(); 

Many other uses of the Pair in the codebase are similarly bad-smelling.

I Googled tuples and they seem to be often misunderstood or used in dubious ways. Is there a convincing argument for or against their use? I can appreciate not wanting to create huge class hierarchies but are there realistic codebases where the class hierarchy would explode if tuples weren't used?

like image 571
Mr. Shiny and New 安宇 Avatar asked Mar 23 '09 21:03

Mr. Shiny and New 安宇


People also ask

What are tuples good for?

A tuple is useful for storing multiple values.. As you note a tuple is just like a list that is immutable - e.g. once created you cannot add/remove/swap elements. One benefit of being immutable is that because the tuple is fixed size it allows the run-time to perform certain optimizations.

Why tuple is more memory efficient?

Because, in CPython, tuples have direct access (pointers) to their elements, while lists need to first access another array that contains the pointers to the elements of the list. Show activity on this post. The main reason for Tuple to be very efficient in reading is because it's immutable.

Why are tuples faster than lists?

Tuples are stored in a single block of memory. Tuples are immutable so, It doesn't require extra space to store new objects. Lists are allocated in two blocks: the fixed one with all the Python object information and a variable-sized block for the data. It is the reason creating a tuple is faster than List.


1 Answers

First of all, a tuple is quick and easy: instead of writing a class for every time you want to put 2 things together, there's a template that does it for you.

Second of all, they're generic. For example, in C++ the std::map uses an std::pair of key and value. Thus ANY pair can be used, instead of having to make some kind of wrapper class with accessor methods for every permutation of two types.

Finally, they're useful for returning multiple values. There's really no reason to make a class specifically for a function's multiple return values, and they shouldn't be treated as one object if they're unrelated.

To be fair, the code you pasted is a bad use of a pair.

like image 167
rlbond Avatar answered Oct 03 '22 00:10

rlbond