用“List”后缀数组有什么好处?对于变量?
我见过许多开发人员在变量名是数组时在变量名后添加“列表”。这有什么意义?您会鼓励这种风格吗?例如:
// 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个想法?可读性——一眼就能看出变量是一个集合。这可以通过变量名的复数形式(即
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).我认为这主要是品味问题。我倾向于为事物命名以反映它们是什么或它们做什么。因此,如果我有一个
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 namedfiles
, or have a more specific name if the context allows it. Naming an array of FilesfileList
is in my humble opinion plain wrong, because, at least in Java, an array is not aList
. But then, the compiler won't complain...More complex collections like a
Map
get names likekeyToValue
. So if I had a map which assigns teachers to classrooms this would be calledteacherToRoom
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.