用“List”后缀数组有什么好处?对于变量?

发布于 2024-10-13 16:12:04 字数 189 浏览 2 评论 0原文

我见过许多开发人员在变量名是数组时在变量名后添加“列表”。这有什么意义?您会鼓励这种风格吗?例如:

// Java
String[] fileList;
String file;

// PHP
$fileList = array();
$file = '';

这个想法适用于任何支持数组的语言。

I have seen numerous developers postfixing variable names with a "List" when it's an array. What's the point of this and would you encourage this style? For example:

// Java
String[] fileList;
String file;

// PHP
$fileList = array();
$file = '';

The idea applies to any language with support for arrays.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月苍老的讽刺 2024-10-20 16:12:04

这个想法?可读性——一眼就能看出变量是一个集合。这可以通过变量名的复数形式(即files)来实现。

如果数据类型是列表这一事实很重要(假设有几种不同的集合类型),那么使用该后缀是正确的做法(而不是简单地作为集合)。

我个人倾向于使用复数变量名称,仅当它添加信息或无法从名称中推断出来时才使用 list 后缀(例如列表列表)。

The idea? Readability - you can tell the variable is a collection in one glance. This can be achieved with pluralizing the variable name (ie. files).

If the fact that the data type is a list is significant (assuming several different collection types), then using that postfix is the right thing to do (as opposed to simply being a collection).

I personally tend to pluralize variable names, using a list postfix only if it adds information or can't be inferred from the name otherwise (say a list of lists).

浊酒尽余欢 2024-10-20 16:12:04

我认为这主要是品味问题。我倾向于为事物命名以反映它们是什么或它们做什么。因此,如果我有一个 File 实例的集合或数组,该变量很可能会命名为 files,或者在上下文允许的情况下具有更具体的名称。在我看来,将文件数组命名为 fileList 是完全错误的,因为至少在 Java 中,数组不是 List。但是,编译器不会抱怨...

更复杂的集合(例如 Map)会得到类似 keyToValue 的名称。因此,如果我有一张将教师分配到教室的地图,那么在我的代码中这将被称为 teacherToRoom。我讨厌通过代码来找出变量的用途,因此我尝试根据需要提供具体的名称。

总之,这一切都与正确的代码有关,从编译器的角度来看,变量名称不会影响此结果。但是,当涉及到使用代码的人员时,它们可以很好地影响结果,因此最好做对大多数代码库工作人员有效的事情。

I think this is mostly a matter of taste. I tend to name things to reflect what they are or what they do. So if I have a collection or array of File instances, the variable would most probably named files, or have a more specific name if the context allows it. Naming an array of Files fileList is in my humble opinion plain wrong, because, at least in Java, an array is not a List. But then, the compiler won't complain...

More complex collections like a Map get names like keyToValue. So if I had a map which assigns teachers to classrooms this would be called teacherToRoom in my code. I hate grepping through the code to find out what the variables are meant to do, so I try to be as specific as needed with the names.

In conclusion it's all about correct code, and variable names can not influence this outcome from the compiler perspective. But they can very well affect the outcome when it comes to humans working with the code, so it's best to do whatever works for the majority of people working on a codebase.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文