为什么使用元组而不是对象? [英] Why use tuples instead of objects?

查看:201
本文介绍了为什么使用元组而不是对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的代码库有一个名为Pair的对象,其中A和B是对中第一个和第二个值的类型。我发现这个对象是冒犯的,因为它被使用,而不是一个明确命名成员的对象。所以我找到这个:

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();
}

而不是

class ProductsOrdered {
  int productId;
  int quantityOrdered;
  // accessor methods, etc
}

List<ProductsOrderded> productsOrdered = blah();

在代码库中对Pair的许多其他用法也是臭味。

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?

推荐答案

首先,一个元组是快速和容易的:而不是为每次你想把2个东西一起编写一个类,有一个模板,它为你。

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.

其次,它们是通用的。例如,在C ++中,std :: map使用了key和value的std :: pair。因此,可以使用任何对,而不必为每种两种类型的排列创建一些具有访问器方法的包装类。

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.

这篇关于为什么使用元组而不是对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆