For instance, take this piece of code:
例如,拿这段代码:
var person = new Person();
or for you Pythonistas:
或者你的Pythonistas:
person = Person()
I'm told constantly how bad this is, but have yet to see an example of the immorality of these two lines of code. To me, person is a Person and trying to give it another name is a waste of time. I suppose in the days before syntax highlighting, this would have been a big deal. But these days, it's pretty easy to tell a type name apart from a variable name. Heck, it's even easy to see the difference here on SO.
我经常被告知这有多糟糕,但还没有看到这两行代码不道德的例子。对我来说,人是一个人,并试图给它另一个名字是浪费时间。我想在语法高亮之前的几天,这将是一个大问题。但是现在,除了变量名之外,很容易告诉类型名称。哎呀,在SO上看到差异很容易。
Or is there something I'm missing? If so, it would be helpful if you could provide an example of code that causes problems.
还是有什么我想念的?如果是这样,如果您能提供导致问题的代码示例,将会很有帮助。
33 个解决方案
#1
What is the reasoning of those telling you this is bad? I do this all the time. It is the simplest, expressive way to name a single variable of a type. If you needed two Person
objects then you could prefix person
with meaningful adjectives like
那些告诉你这个坏的原因是什么?我一直这样做。命名单个变量的类型是最简单,最富有表现力的方法。如果你需要两个Person对象,那么你可以为人们添加有意义的形容词
fastPerson
slowPerson
otherwise just
person
is fine with me.
对我很好。
#2
I use this pattern a lot in method signatures. If I'm unable to provide an alternate descriptive name then IMHO, there is nothing wrong with this.
我在方法签名中经常使用这种模式。如果我无法提供备用描述性名称,那么恕我直言,这没有任何问题。
What is wrong would be if you have two types Person and person then that is very very wrong.
如果你有两种类型的人和人那么这是非常错误的。
#3
I use it all the time for temporary object references. I would avoid it like the plague for primitive data types.
我一直用它来进行临时对象引用。我会像原始数据类型的瘟疫一样避免它。
Person person = new Person(); // okay
int Int = 42; // pure evil
#4
If someone says that is evil, ask them if this is better:
如果有人说这是邪恶的,请问他们这是否更好:
var abc = new Person();
#5
If the Person is a general Person in the context, then "person" is a really good name. Of course if the Person has a specific role in the code then it's better to name her using the role.
如果Person是上下文中的普通人,那么“person”就是一个非常好的名字。当然,如果Person在代码中具有特定角色,那么最好使用该角色来命名她。
#6
I suppose I'll get downvoted for saying so, but ...
我想我会因为这样说而被投票,但......
Having just come through a century witnessing epic murder and greed, we programmers are truly blessed if the most immoral thing we can do is name a variable.
刚刚经历了一个世纪见证了史诗般的谋杀和贪婪,如果我们能做的最不道德的事情就是命名变量,那么程序员真的很幸运。
#7
I don't think it's necessarily "bad", but obviously if you can qualify it to give it more context, like what sort of person it is (you are dealing with only one of presumably many possible persons), then someone else picking it up may understand better.
我认为这不一定是“坏”,但很明显,如果你有资格给它更多的背景,比如它是什么样的人(你只与一个可能是许多可能的人打交道),然后别人选择它起来可能会更好理解。
#8
Jason - I'm not sure who has told you that this is bad. A number of authors use this as a standard way of expressing an Instance (lower case) of a Class (capitalized).
杰森 - 我不确定是谁告诉你这很糟糕。许多作者使用它作为表达类(大写)的实例(小写)的标准方式。
I use this quite often as I find that the lower-cased variable actually communicates to me not only that this is an instance but also the name of the class.
我经常使用这个,因为我发现低级变量实际上与我通信不仅是这是一个实例而且是类的名称。
Unless someone has a solid argument to the contrary, I'll certainly continue doing this.
除非有人有相反的坚定论据,否则我肯定会继续这样做。
#9
The reason it is considered bad is if you need to have 2 Person's in the future, you can then end up with code that looks like.
它被认为是坏的原因是如果你将来需要2个人,你可以得到看起来像的代码。
Person person = new Person();
人人=新人();
Person person2 = new Person();
Person person2 = new Person();
That would then be bordering on "Bad". However, in that case you should then refactor your orginal person in order to distinguish between the two.
那将是接近“坏”。但是,在这种情况下,您应该重构您的原始人,以便区分这两者。
As for your example, the variable name "person" is a perfectly descriptive name for the object "Person". Therefore there is nothing wrong with it whatsoever.
至于您的示例,变量名称“person”是对象“Person”的完全描述性名称。因此,它没有任何问题。
#10
I say name for what it is: if the variable represents a person with 2 dogs, call it personWith2Dogs
. It the variable has short scope (like a loop var) then person is fine.
我说的是它的名字:如果变量代表一个有2只狗的人,则称之为personWith2Dogs。变量具有短范围(如循环变量)然后人很好。
#11
I use that a lot in my code, and don't think there is anything wrong with it. That said, I (probably) wouldn't use it in a method longer than, say one screen, and if there are multiple instances of Person class. Definitely don't name them person1, person2, person3... instead use something more descriptive, like person_to_del, person_to_ban, person_to_update, etc.
我在代码中使用了很多,并且认为它没有任何问题。也就是说,我(可能)不会在比一个屏幕更长的方法中使用它,并且如果有多个Person类实例。绝对不要将它们命名为person1,person2,person3 ......而是使用更具描述性的内容,例如person_to_del,person_to_ban,person_to_update等。
#12
Not immoral, but a global search will find both Person
and person
if you fail to activate case-sensitivity. I prefer a prefix to make global search/replace easier, but absolutely NOT Hungarian or something long/complicated. So, I use...
不是不道德的,但如果你不能激活区分大小写的话,全局搜索会找到人和人。我更喜欢使用前缀来使全局搜索/替换更容易,但绝对不是匈牙利语或长/复杂的东西。所以,我用......
Person
for the class/type aPerson
for a local variable thePerson
for a method parameter myPerson
for an instance variable ourPerson
for a class variable
类的人/类型aPerson用于局部变量thePerson用于方法参数myPerson用于实例变量myPerson用于类变量
On rare occasion, I might use p
in a local context where I have LOTS of references, but that usually only applies to loop indexes and the like.
在极少数情况下,我可能在本地上下文中使用p,其中我有很多引用,但这通常只适用于循环索引等。
#13
It depends.
If you have a strict capitalization style, so variables begin lowercase (and use either under_scores or camelCase for word breaks), and Classes begin with Capital Letters, then it's obvious that person is a variable and Person is a class, and when somebody understand this, they won't seem to be in overlapping namespaces. (Similarly, people almost never get confused between the verb or noun "polish" and the adjective "Polish".)
如果你有一个严格的大写风格,那么变量开始小写(并使用under_scores或camelCase进行分词),而Classes以大写字母开头,那么很明显person是变量而Person是一个类,当有人理解这个时,它们似乎不会在重叠的命名空间中。 (同样,人们几乎从不会在动词或名词“波兰语”和形容词“波兰语”之间混淆。)
If you don't have such a style, then you've got two names that can easily be confused, and differ only in case. That's bad.
如果你没有这样的风格,那么你有两个很容易混淆的名字,并且只有大小写才有区别。那很糟。
#14
What are the exact arguments those people use?
这些人使用的确切论据是什么?
If they don't allow you to use person as a variable name, you might consider to add the 'a' prefix.
如果他们不允许您将person用作变量名,则可以考虑添加“a”前缀。
aPerson = Person()
#15
I think what you are doing is fine. I think in general it's important to have agreed coding standards.
我觉得你做的很好。我认为一般来说,达成一致的编码标准非常重要。
For instance I use lowerCamelCase for instances, variables and UpperCamelCase for classes e.t.c.
例如,我使用lowerCamelCase作为实例,变量和UpperCamelCase用于类e.t.c.
Coding standards should remove this problem.
编码标准应该消除这个问题。
When I look at succesful open source programs they often have coding standards
当我看到成功的开源程序时,他们通常会有编码标准
http://drupal.org/coding-standards
http://help.joomla.org/content/view/826/125/
http://wiki.rubyonrails.org/rails/pages/CodingStandards
http://lxr.linux.no/linux/Documentation/CodingStyle
Agreeing the coding standards should be the last battle you have over this.
同意编码标准应该是你对此的最后一场战斗。
In fact look at the wikipedia entry (from http://en.wikipedia.org/wiki/CamelCase)
实际上看*条目(来自http://en.wikipedia.org/wiki/CamelCase)
Programming and coding style
编程和编码风格
Internal capitalization is sometimes recommended to indicate word boundaries by the coding style guidelines for writing source code (e.g., the Mesa programming language and the Java programming language). The recommendations contained in some of these guidelines are supported by static analysis tools that check source code for adherence.
有时建议使用内部大写来通过编写源代码的编码样式指南(例如,Mesa编程语言和Java编程语言)来指示字边界。静态分析工具支持其中一些指南中包含的建议,这些工具可检查源代码是否符合要求。
These recommendations often distinguish between UpperCamelCase and lowerCamelCase, typically specifying which variety should be used for specific kinds of entities: variables, record fields, methods, procedures, types, etc.
这些建议通常区分UpperCamelCase和lowerCamelCase,通常指定应该为特定类型的实体使用哪种变体:变量,记录字段,方法,过程,类型等。
One widely used Java coding style dictates that UpperCamelCase be used for classes, and lowerCamelCase be used for instances and methods.[19] Recognising this usage, some IDEs, such as Eclipse, implement shortcuts based on CamelCase. For instance, in Eclipse's Content assist feature, typing just the upper-case letters of a CamelCase word will suggest any matching class or method name (for example, typing "NPE" and activating content assist could suggest "NullPointerException").
一种广泛使用的Java编码风格规定UpperCamelCase用于类,而lowerCamelCase用于实例和方法。[19]认识到这种用法,一些IDE(如Eclipse)实现了基于CamelCase的快捷方式。例如,在Eclipse的内容辅助功能中,只键入CamelCase单词的大写字母将建议任何匹配的类或方法名称(例如,键入“NPE”并激活内容辅助可能会建议“NullPointerException”)。
The original Hungarian notation for programming specifies that a lowercase abbreviation for the "usage type" (not data type) should prefix all variable names, with the remainder of the name in UpperCamelCase; as such it is a form of lowerCamelCase. CamelCase is the official convention for file names in Java and for the Amiga personal computer.
编程的原始匈牙利表示法指定“使用类型”(不是数据类型)的小写缩写应该在所有变量名称前面加上,其余名称在UpperCamelCase中;因此它是lowerCamelCase的一种形式。 CamelCase是Java和Amiga个人计算机中文件名的官方约定。
Microsoft .NET recommends lowerCamelCase for parameters and non-public fields and UpperCamelCase (aka "Pascal Style") for other types of identifiers.[20]
Microsoft .NET建议使用lowerCamelCase作为参数和非公共字段,使用UpperCamelCase(也称为“Pascal Style”)作为其他类型的标识符。[20]
Python recommends UpperCamelCase for class names.[21]
Python为类名推荐了UpperCamelCase。[21]
The NIEM registry requires that XML Data Elements use UpperCamelCase and XML Attributes use lowerCamelCase.
NIEM注册表要求XML数据元素使用UpperCamelCase,XML属性使用lowerCamelCase。
There is no single convention for the inclusion of upper case abbreviations (mainly acronyms and initialisms) within CamelCase names. Approaches include leaving the whole abbreviation in upper case (such as in "useHTTPConnection") and leaving only the first letter in upper case (such as in "useHttpConnection").
在CamelCase名称中包含大写缩写(主要是首字母缩略词和首字母缩写词)没有单一的约定。方法包括将整个缩写保留为大写(例如在“useHTTPConnection”中)并且仅保留大写的第一个字母(例如在“useHttpConnection”中)。
Camel case is by no means universal in computing. Users of several modern programming languages, notably those in the Lisp and Forth families, nearly always use hyphens. Among the reasons sometimes given are that doing so does not require shifting on most keyboards, that the words are more readable when they are separated, and that camel case may simply not be reliably preserved in case-insensitive or case-folding languages (such as Common Lisp, that, while technically a case-sensitive language, canonicalizes (folds) identifiers to uppercase by default).
骆驼案在计算方面绝不是普遍的。几种现代编程语言的用户,尤其是Lisp和Forth系列语言的用户,几乎总是使用连字符。有时给出的原因之一是这样做并不需要在大多数键盘上移位,这些单词在分离时更具可读性,并且在不区分大小写或大小写折叠的语言中可能无法可靠地保留camel case(例如Common Lisp,虽然在技术上是一种区分大小写的语言,但默认情况下将标识符(折叠)标准化为大写。
#16
It's possible to make a stronger argument that method names of that kind are not only harmless but can be an indicator of good quality code.
有可能提出一个更强有力的论据,即那种方法名称不仅无害,而且可以作为高质量代码的指标。
-
An indicator of good code granularity: If your methods are short, single-purpose, and descriptively named, you don't need a lot of information in variable names. If you have long methods that do a lot of things and need to keep track of a lot of context and state, then your variable names need to be more descriptive.
良好代码粒度的指标:如果您的方法简短,单一用途且描述性命名,则不需要变量名称中的大量信息。如果你有很多方法可以做很多事情并且需要跟踪大量的上下文和状态,那么你的变量名需要更具描述性。
-
An indicator of general-purpose calculations being pushed down into general-purpose methods: if you do an intermediate manipulation of data structures in a business method, for example an array of users has to be deduplicated, you'll have to have variables in scope with names like
users[]
anddeduplicatedUsers[]
. If you move the deduplication to a utility method, you can call the methodUtils.dedup(array)
, and you can call the deduplicated arraydeduplicatedArray
or justresult
.将通用计算的指标推送到通用方法中:如果在业务方法中对数据结构进行中间操作,例如必须对用户数组进行重复数据删除,则必须在范围内包含变量名称如users []和deduplicatedUsers []。如果将重复数据删除移动到实用程序方法,则可以调用方法Utils.dedup(array),并且可以调用重复数据删除的数组deduplicatedArray或仅调用结果。
-
Java decompilers often use a scheme like that for naming local variables (instance and class variables are normally available in the bytecode, but local variables aren't), and the results are more readable than you might expect, in fact often more readable than the original source.
Java反编译器通常使用这样的方案来命名局部变量(实例和类变量通常在字节码中可用,但局部变量不可用),并且结果比您预期的更具可读性,实际上通常比原始来源。
-
See Larry Wall's principle of "Local Ambiguity is OK" - http://www.wall.org/~larry/natural.html .
参见拉里沃尔的“局部歧义是正常的”原则 - http://www.wall.org/~larry/natural.html。
#17
I'd say that you probably have some specific use in mind whenever you create an object. The type alone very rarely reflects that use.
我会说你在创建一个对象时可能会有一些特定的用途。仅这种类型很少反映这种用途。
So if you want to create a new contact in your address book application, you might want to call the variable newContact
.
因此,如果要在地址簿应用程序中创建新联系人,可能需要调用变量newContact。
And if you're unit testing your code to check the behaviour of Person
objects with no names set, you might want to call them unnamedPerson
or something similar.
如果您对代码进行单元测试以检查未设置名称的Person对象的行为,则可能需要将它们称为unnamedPerson或类似的东西。
Calling it simply person
forgoes a big chance to make your code self-documenting.
简单地称它为人们放弃了使代码自我记录的大好机会。
#18
Only if you're programming in VB6. In that case, what you're doing is illegal, but not immoral.
只有你在VB6编程。在这种情况下,你所做的是非法的,但不是不道德的。
#19
I do it as well, and neither do I understand why it should be 'immoral'. Though I can understand that it 'might' sometimes be confusing, but today we have IDE's with intellisense and syntax highlighting which will make sure that (if you make a mistake and reference your variable instead of your class, and vice versa) you'll see your error quite fast. And we also have the compiler. :)
我也这样做,我也不理解为什么它应该是“不道德的”。虽然我可以理解它“可能”有时会令人困惑,但今天我们有IDE的intellisense和语法高亮,这将确保(如果你犯了一个错误并引用你的变量而不是你的类,反之亦然)你会很快看到你的错误。我们也有编译器。 :)
#20
I also don't see any problem with this practice. As long as there is only one variable of that class, it is easy to write and easy read. Imo, that even applies in a basic text editor. I personally can't recall anyone calling this bad or even immoral. Just continue doing this :)
我也没有看到这种做法有任何问题。只要该类只有一个变量,就可以轻松编写并轻松阅读。 Imo,甚至适用于基本的文本编辑器。我个人不记得有人称这种不好甚至是不道德的。继续这样做:)
#21
I think the 'rule' you may be thinking of is intended more for primitive types, and classes where the class name makes a poor variable name.
我认为你可能想到的'规则'更适用于原始类型,以及类名称变量名称较差的类。
For example, if you were dealing with calculating the cost of a particular item in an online store, the following code would not be good form:
例如,如果您正在处理计算在线商店中特定商品的成本,则以下代码将不是良好的形式:
Decimal _decimal = item.BaseCost + item.Tax;
Instead, a more descriptive name would be advised, such as '_total' , or '_cost'.
相反,建议使用更具描述性的名称,例如'_total'或'_cost'。
#22
The only issue with this sort of thing I've found is if you want the same name for a private member and also a public property.
我发现这种事情的唯一问题是,如果你想为私人会员和公共财产提供相同的名称。
If these differ only in case, it'll work fine in case-sensitive languages such as C#, but not in VB.NET.
如果它们的区别仅在于大小写,它在C#等区分大小写的语言中可以正常工作,但在VB.NET中则不行。
So, for instance, in VB, I'd write
所以,例如,在VB中,我会写
Private _name As String
but
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property
I'd do the same in C#, so that translation from one to the other is painless. It also makes it a bit less error-prone, since it's very easy to mis-read, or indeed mis-type words that differ only by case.
我会在C#中做同样的事情,所以从一个到另一个的翻译是无痛的。它也使它更容易出错,因为它很容易被误读,或者确实是错误输入只有大小写不同的单词。
#23
Not immoral, but if your best name for your variable is the name of the type, something wrong or you just making a proof of concept or something like that. For me a variable name must refer to the meaning in the business context and not to the programming language. It will be more difficult to understand the code.
不是不道德的,但如果你的变量的最佳名称是类型的名称,错误的东西,或者你只是做出概念证明或类似的东西。对我来说,变量名必须引用业务环境中的含义而不是编程语言。理解代码会更加困难。
#24
I often use Person person = new Person()
myself. Commonly used in Java/C#.
我经常使用Person person = new Person()。常用于Java / C#。
Although I ended up wondering yesterday why
虽然我最后想知道为什么
private enum DataType {NEW, OLD}
doesn't work in C#...
在C#中不起作用...
Especially seeing how you can use String
, string
, Double
, double
,... at will in C#.
特别是看看如何在C#中随意使用String,string,Double,double,...
#25
Person person = new Person()
is fine in my book.
在我的书中很好。
Wheh it becomes horrible is when you have:
可怕的是,当你有:
string Person;
string person;
Very easy to mix up the 2.
非常容易混淆2。
#26
What has been expressed to me, other then not meeting our Coding Standards, is avoiding adding confusion when someone else is reading my code. I, personally, see no problem with it, as long as the meaning is clear.
除了满足我们的编码标准之外,我所表达的是避免在其他人阅读我的代码时引起混淆。我个人认为没有问题,只要意思清楚。
As for CLR types (int,string, etc.) you can use either String or string (etc.) to declare the type, so I would avoid using something like
对于CLR类型(int,string等),你可以使用String或string(等)来声明类型,所以我会避免使用像
int Int = 0;
string String = "hi there";
#27
Making capitalization the only difference is dangerous...keep doing this for a big project and I guarantee you'll run into bizarre errors you can't seem to locate.
将资本化作为唯一的区别是危险的...继续为一个大项目做这个,我保证你会遇到你似乎无法找到的奇怪错误。
fastPerson/slowPerson like above are fine...they're descriptive and differentiated from the variable type name...but come on man, calling an int "Int" would be plain lazy.
像上面这样的fastPerson / slowPerson很好......它们是描述性的,并且与变量类型名称有区别......但是来吧,调用int“Int”将是非常懒惰的。
#28
I would say its never immoral - it really just your base line variable name. If you can't think of a better name, naming it after it's type is a good default.(For complex types only - for built in types its evil) And lots of time there really isn't a better name cause you don't know anything else about the variable. Like with this method
我会说它永远不道德 - 它只是你的基线变量名。如果你想不出一个更好的名字,在它的类型之后命名它是一个很好的默认值。(仅适用于复杂类型 - 内置类型它的邪恶)而且很多时候真的没有一个更好的名字因为你不'我对变量一无所知。喜欢这种方法
void SaveToDatabase(Person person) {...}
About the only thing else you could reasonably call person is person_to_save
or something like that which seems redundant.
关于你可以合理地称之为人的另一件事是person_to_save或类似的东西似乎是多余的。
However in a lot of cases you can improve on the readability of your code by replacing person with a more descriptive name. For example this is less descriptive
但是,在很多情况下,您可以通过使用更具描述性的名称替换人来提高代码的可读性。例如,这不太具描述性
void AddToAccount(Account account, Person person) {...}
than this
void AddToAccount(Account account, Person dependent) {...}
However please, please - pretty please don't put an 'a' or 't' in front of the type name. I.E. aPerson for 'a person' or tPerson for 'the person'. Its overly complicated and doesn't add much if any value. Plus you starts to pollute you scope with a bunch of variables that start with a or t which can minimize the value of intelli-sense.
不过请拜托 - 请不要在类型名称前加上'a'或't'。 I.E. aPerson为'一个人'或tPerson为'这个人'。它过于复杂,并没有增加太多的价值。另外,你开始用一堆以a或t开头的变量来污染你的范围,这些变量可以最小化智能的价值。
#29
I wouldn't say it's horrible. I usually prefix the name of the variable with 'a' in this sort of thing to show that it's a single instance of the type, so I would do
我不会说这太可怕了。我通常在变量的名称前加上'a'来表示这是一个类型的单个实例,所以我会做
Person aPerson = new Person();
It makes the code read more naturally I think.
它让我认为代码读得更自然。
#30
Absolutely nothing wrong with it subject to caveats pointed out by others (summarizing here for convenience): not doing it with primitive types, refactoring the original instance if another instance is added later, not using char-case to differentiate class names, etc.
绝对没有任何问题,但受其他人指出的注意事项(为方便起见):不使用原始类型,如果稍后添加另一个实例则重构原始实例,不使用char-case来区分类名等。
My rule of thumb? Statements in code should read like simple English sentences.
我的经验法则?代码中的语句应该像简单的英语句子一样。
Person person = new Person();
人人=新人();
Employee employee = person.getRole(EMPLOYEE);
员工雇员= person.getRole(EMPLOYEE);
Parent parent = person.getRole(PARENT);
父母= person.getRole(PARENT);
person.getFullName();
employee.getSalary();
parent.getChildren();
parent.getFullName(); // assuming decorator pattern at play
parent.getFullName(); //假设装饰模式在游戏中
if (person.hasRole(EMPLOYEE)) {
if(person.hasRole(EMPLOYEE)){
...
}
And so forth.
等等。
If the variable's scope is limited (the encapsulating method is 10-15 lines, for instance) I might even use 'p' instead of 'person'. Shorter variable names are less of a distraction when trying to hold context in your head. Avoid gratuitous prefixes such as 'a' or (shudder) Hungarian notation and offshoots thereof. (Mind you, I have nothing against such prefixes when used in the appropriate context - C++ / COM / ATL / Win32 API code etc., where it helps to keep assignments / typecasting straight).
如果变量的范围有限(例如,封装方法是10-15行),我甚至可能使用'p'而不是'person'。在尝试保持头脑中的上下文时,较短的变量名称不会分散注意力。避免使用诸如“a”或(颤抖)匈牙利符号及其分支之类的免费前缀。 (请注意,在适当的上下文中使用时,我没有反对这些前缀 - C ++ / COM / ATL / Win32 API代码等,它有助于保持分配/类型转换直接)。
My two(!) bits :-)
我的两个(!)位:-)
#1
What is the reasoning of those telling you this is bad? I do this all the time. It is the simplest, expressive way to name a single variable of a type. If you needed two Person
objects then you could prefix person
with meaningful adjectives like
那些告诉你这个坏的原因是什么?我一直这样做。命名单个变量的类型是最简单,最富有表现力的方法。如果你需要两个Person对象,那么你可以为人们添加有意义的形容词
fastPerson
slowPerson
otherwise just
person
is fine with me.
对我很好。
#2
I use this pattern a lot in method signatures. If I'm unable to provide an alternate descriptive name then IMHO, there is nothing wrong with this.
我在方法签名中经常使用这种模式。如果我无法提供备用描述性名称,那么恕我直言,这没有任何问题。
What is wrong would be if you have two types Person and person then that is very very wrong.
如果你有两种类型的人和人那么这是非常错误的。
#3
I use it all the time for temporary object references. I would avoid it like the plague for primitive data types.
我一直用它来进行临时对象引用。我会像原始数据类型的瘟疫一样避免它。
Person person = new Person(); // okay
int Int = 42; // pure evil
#4
If someone says that is evil, ask them if this is better:
如果有人说这是邪恶的,请问他们这是否更好:
var abc = new Person();
#5
If the Person is a general Person in the context, then "person" is a really good name. Of course if the Person has a specific role in the code then it's better to name her using the role.
如果Person是上下文中的普通人,那么“person”就是一个非常好的名字。当然,如果Person在代码中具有特定角色,那么最好使用该角色来命名她。
#6
I suppose I'll get downvoted for saying so, but ...
我想我会因为这样说而被投票,但......
Having just come through a century witnessing epic murder and greed, we programmers are truly blessed if the most immoral thing we can do is name a variable.
刚刚经历了一个世纪见证了史诗般的谋杀和贪婪,如果我们能做的最不道德的事情就是命名变量,那么程序员真的很幸运。
#7
I don't think it's necessarily "bad", but obviously if you can qualify it to give it more context, like what sort of person it is (you are dealing with only one of presumably many possible persons), then someone else picking it up may understand better.
我认为这不一定是“坏”,但很明显,如果你有资格给它更多的背景,比如它是什么样的人(你只与一个可能是许多可能的人打交道),然后别人选择它起来可能会更好理解。
#8
Jason - I'm not sure who has told you that this is bad. A number of authors use this as a standard way of expressing an Instance (lower case) of a Class (capitalized).
杰森 - 我不确定是谁告诉你这很糟糕。许多作者使用它作为表达类(大写)的实例(小写)的标准方式。
I use this quite often as I find that the lower-cased variable actually communicates to me not only that this is an instance but also the name of the class.
我经常使用这个,因为我发现低级变量实际上与我通信不仅是这是一个实例而且是类的名称。
Unless someone has a solid argument to the contrary, I'll certainly continue doing this.
除非有人有相反的坚定论据,否则我肯定会继续这样做。
#9
The reason it is considered bad is if you need to have 2 Person's in the future, you can then end up with code that looks like.
它被认为是坏的原因是如果你将来需要2个人,你可以得到看起来像的代码。
Person person = new Person();
人人=新人();
Person person2 = new Person();
Person person2 = new Person();
That would then be bordering on "Bad". However, in that case you should then refactor your orginal person in order to distinguish between the two.
那将是接近“坏”。但是,在这种情况下,您应该重构您的原始人,以便区分这两者。
As for your example, the variable name "person" is a perfectly descriptive name for the object "Person". Therefore there is nothing wrong with it whatsoever.
至于您的示例,变量名称“person”是对象“Person”的完全描述性名称。因此,它没有任何问题。
#10
I say name for what it is: if the variable represents a person with 2 dogs, call it personWith2Dogs
. It the variable has short scope (like a loop var) then person is fine.
我说的是它的名字:如果变量代表一个有2只狗的人,则称之为personWith2Dogs。变量具有短范围(如循环变量)然后人很好。
#11
I use that a lot in my code, and don't think there is anything wrong with it. That said, I (probably) wouldn't use it in a method longer than, say one screen, and if there are multiple instances of Person class. Definitely don't name them person1, person2, person3... instead use something more descriptive, like person_to_del, person_to_ban, person_to_update, etc.
我在代码中使用了很多,并且认为它没有任何问题。也就是说,我(可能)不会在比一个屏幕更长的方法中使用它,并且如果有多个Person类实例。绝对不要将它们命名为person1,person2,person3 ......而是使用更具描述性的内容,例如person_to_del,person_to_ban,person_to_update等。
#12
Not immoral, but a global search will find both Person
and person
if you fail to activate case-sensitivity. I prefer a prefix to make global search/replace easier, but absolutely NOT Hungarian or something long/complicated. So, I use...
不是不道德的,但如果你不能激活区分大小写的话,全局搜索会找到人和人。我更喜欢使用前缀来使全局搜索/替换更容易,但绝对不是匈牙利语或长/复杂的东西。所以,我用......
Person
for the class/type aPerson
for a local variable thePerson
for a method parameter myPerson
for an instance variable ourPerson
for a class variable
类的人/类型aPerson用于局部变量thePerson用于方法参数myPerson用于实例变量myPerson用于类变量
On rare occasion, I might use p
in a local context where I have LOTS of references, but that usually only applies to loop indexes and the like.
在极少数情况下,我可能在本地上下文中使用p,其中我有很多引用,但这通常只适用于循环索引等。
#13
It depends.
If you have a strict capitalization style, so variables begin lowercase (and use either under_scores or camelCase for word breaks), and Classes begin with Capital Letters, then it's obvious that person is a variable and Person is a class, and when somebody understand this, they won't seem to be in overlapping namespaces. (Similarly, people almost never get confused between the verb or noun "polish" and the adjective "Polish".)
如果你有一个严格的大写风格,那么变量开始小写(并使用under_scores或camelCase进行分词),而Classes以大写字母开头,那么很明显person是变量而Person是一个类,当有人理解这个时,它们似乎不会在重叠的命名空间中。 (同样,人们几乎从不会在动词或名词“波兰语”和形容词“波兰语”之间混淆。)
If you don't have such a style, then you've got two names that can easily be confused, and differ only in case. That's bad.
如果你没有这样的风格,那么你有两个很容易混淆的名字,并且只有大小写才有区别。那很糟。
#14
What are the exact arguments those people use?
这些人使用的确切论据是什么?
If they don't allow you to use person as a variable name, you might consider to add the 'a' prefix.
如果他们不允许您将person用作变量名,则可以考虑添加“a”前缀。
aPerson = Person()
#15
I think what you are doing is fine. I think in general it's important to have agreed coding standards.
我觉得你做的很好。我认为一般来说,达成一致的编码标准非常重要。
For instance I use lowerCamelCase for instances, variables and UpperCamelCase for classes e.t.c.
例如,我使用lowerCamelCase作为实例,变量和UpperCamelCase用于类e.t.c.
Coding standards should remove this problem.
编码标准应该消除这个问题。
When I look at succesful open source programs they often have coding standards
当我看到成功的开源程序时,他们通常会有编码标准
http://drupal.org/coding-standards
http://help.joomla.org/content/view/826/125/
http://wiki.rubyonrails.org/rails/pages/CodingStandards
http://lxr.linux.no/linux/Documentation/CodingStyle
Agreeing the coding standards should be the last battle you have over this.
同意编码标准应该是你对此的最后一场战斗。
In fact look at the wikipedia entry (from http://en.wikipedia.org/wiki/CamelCase)
实际上看*条目(来自http://en.wikipedia.org/wiki/CamelCase)
Programming and coding style
编程和编码风格
Internal capitalization is sometimes recommended to indicate word boundaries by the coding style guidelines for writing source code (e.g., the Mesa programming language and the Java programming language). The recommendations contained in some of these guidelines are supported by static analysis tools that check source code for adherence.
有时建议使用内部大写来通过编写源代码的编码样式指南(例如,Mesa编程语言和Java编程语言)来指示字边界。静态分析工具支持其中一些指南中包含的建议,这些工具可检查源代码是否符合要求。
These recommendations often distinguish between UpperCamelCase and lowerCamelCase, typically specifying which variety should be used for specific kinds of entities: variables, record fields, methods, procedures, types, etc.
这些建议通常区分UpperCamelCase和lowerCamelCase,通常指定应该为特定类型的实体使用哪种变体:变量,记录字段,方法,过程,类型等。
One widely used Java coding style dictates that UpperCamelCase be used for classes, and lowerCamelCase be used for instances and methods.[19] Recognising this usage, some IDEs, such as Eclipse, implement shortcuts based on CamelCase. For instance, in Eclipse's Content assist feature, typing just the upper-case letters of a CamelCase word will suggest any matching class or method name (for example, typing "NPE" and activating content assist could suggest "NullPointerException").
一种广泛使用的Java编码风格规定UpperCamelCase用于类,而lowerCamelCase用于实例和方法。[19]认识到这种用法,一些IDE(如Eclipse)实现了基于CamelCase的快捷方式。例如,在Eclipse的内容辅助功能中,只键入CamelCase单词的大写字母将建议任何匹配的类或方法名称(例如,键入“NPE”并激活内容辅助可能会建议“NullPointerException”)。
The original Hungarian notation for programming specifies that a lowercase abbreviation for the "usage type" (not data type) should prefix all variable names, with the remainder of the name in UpperCamelCase; as such it is a form of lowerCamelCase. CamelCase is the official convention for file names in Java and for the Amiga personal computer.
编程的原始匈牙利表示法指定“使用类型”(不是数据类型)的小写缩写应该在所有变量名称前面加上,其余名称在UpperCamelCase中;因此它是lowerCamelCase的一种形式。 CamelCase是Java和Amiga个人计算机中文件名的官方约定。
Microsoft .NET recommends lowerCamelCase for parameters and non-public fields and UpperCamelCase (aka "Pascal Style") for other types of identifiers.[20]
Microsoft .NET建议使用lowerCamelCase作为参数和非公共字段,使用UpperCamelCase(也称为“Pascal Style”)作为其他类型的标识符。[20]
Python recommends UpperCamelCase for class names.[21]
Python为类名推荐了UpperCamelCase。[21]
The NIEM registry requires that XML Data Elements use UpperCamelCase and XML Attributes use lowerCamelCase.
NIEM注册表要求XML数据元素使用UpperCamelCase,XML属性使用lowerCamelCase。
There is no single convention for the inclusion of upper case abbreviations (mainly acronyms and initialisms) within CamelCase names. Approaches include leaving the whole abbreviation in upper case (such as in "useHTTPConnection") and leaving only the first letter in upper case (such as in "useHttpConnection").
在CamelCase名称中包含大写缩写(主要是首字母缩略词和首字母缩写词)没有单一的约定。方法包括将整个缩写保留为大写(例如在“useHTTPConnection”中)并且仅保留大写的第一个字母(例如在“useHttpConnection”中)。
Camel case is by no means universal in computing. Users of several modern programming languages, notably those in the Lisp and Forth families, nearly always use hyphens. Among the reasons sometimes given are that doing so does not require shifting on most keyboards, that the words are more readable when they are separated, and that camel case may simply not be reliably preserved in case-insensitive or case-folding languages (such as Common Lisp, that, while technically a case-sensitive language, canonicalizes (folds) identifiers to uppercase by default).
骆驼案在计算方面绝不是普遍的。几种现代编程语言的用户,尤其是Lisp和Forth系列语言的用户,几乎总是使用连字符。有时给出的原因之一是这样做并不需要在大多数键盘上移位,这些单词在分离时更具可读性,并且在不区分大小写或大小写折叠的语言中可能无法可靠地保留camel case(例如Common Lisp,虽然在技术上是一种区分大小写的语言,但默认情况下将标识符(折叠)标准化为大写。
#16
It's possible to make a stronger argument that method names of that kind are not only harmless but can be an indicator of good quality code.
有可能提出一个更强有力的论据,即那种方法名称不仅无害,而且可以作为高质量代码的指标。
-
An indicator of good code granularity: If your methods are short, single-purpose, and descriptively named, you don't need a lot of information in variable names. If you have long methods that do a lot of things and need to keep track of a lot of context and state, then your variable names need to be more descriptive.
良好代码粒度的指标:如果您的方法简短,单一用途且描述性命名,则不需要变量名称中的大量信息。如果你有很多方法可以做很多事情并且需要跟踪大量的上下文和状态,那么你的变量名需要更具描述性。
-
An indicator of general-purpose calculations being pushed down into general-purpose methods: if you do an intermediate manipulation of data structures in a business method, for example an array of users has to be deduplicated, you'll have to have variables in scope with names like
users[]
anddeduplicatedUsers[]
. If you move the deduplication to a utility method, you can call the methodUtils.dedup(array)
, and you can call the deduplicated arraydeduplicatedArray
or justresult
.将通用计算的指标推送到通用方法中:如果在业务方法中对数据结构进行中间操作,例如必须对用户数组进行重复数据删除,则必须在范围内包含变量名称如users []和deduplicatedUsers []。如果将重复数据删除移动到实用程序方法,则可以调用方法Utils.dedup(array),并且可以调用重复数据删除的数组deduplicatedArray或仅调用结果。
-
Java decompilers often use a scheme like that for naming local variables (instance and class variables are normally available in the bytecode, but local variables aren't), and the results are more readable than you might expect, in fact often more readable than the original source.
Java反编译器通常使用这样的方案来命名局部变量(实例和类变量通常在字节码中可用,但局部变量不可用),并且结果比您预期的更具可读性,实际上通常比原始来源。
-
See Larry Wall's principle of "Local Ambiguity is OK" - http://www.wall.org/~larry/natural.html .
参见拉里沃尔的“局部歧义是正常的”原则 - http://www.wall.org/~larry/natural.html。
#17
I'd say that you probably have some specific use in mind whenever you create an object. The type alone very rarely reflects that use.
我会说你在创建一个对象时可能会有一些特定的用途。仅这种类型很少反映这种用途。
So if you want to create a new contact in your address book application, you might want to call the variable newContact
.
因此,如果要在地址簿应用程序中创建新联系人,可能需要调用变量newContact。
And if you're unit testing your code to check the behaviour of Person
objects with no names set, you might want to call them unnamedPerson
or something similar.
如果您对代码进行单元测试以检查未设置名称的Person对象的行为,则可能需要将它们称为unnamedPerson或类似的东西。
Calling it simply person
forgoes a big chance to make your code self-documenting.
简单地称它为人们放弃了使代码自我记录的大好机会。
#18
Only if you're programming in VB6. In that case, what you're doing is illegal, but not immoral.
只有你在VB6编程。在这种情况下,你所做的是非法的,但不是不道德的。
#19
I do it as well, and neither do I understand why it should be 'immoral'. Though I can understand that it 'might' sometimes be confusing, but today we have IDE's with intellisense and syntax highlighting which will make sure that (if you make a mistake and reference your variable instead of your class, and vice versa) you'll see your error quite fast. And we also have the compiler. :)
我也这样做,我也不理解为什么它应该是“不道德的”。虽然我可以理解它“可能”有时会令人困惑,但今天我们有IDE的intellisense和语法高亮,这将确保(如果你犯了一个错误并引用你的变量而不是你的类,反之亦然)你会很快看到你的错误。我们也有编译器。 :)
#20
I also don't see any problem with this practice. As long as there is only one variable of that class, it is easy to write and easy read. Imo, that even applies in a basic text editor. I personally can't recall anyone calling this bad or even immoral. Just continue doing this :)
我也没有看到这种做法有任何问题。只要该类只有一个变量,就可以轻松编写并轻松阅读。 Imo,甚至适用于基本的文本编辑器。我个人不记得有人称这种不好甚至是不道德的。继续这样做:)
#21
I think the 'rule' you may be thinking of is intended more for primitive types, and classes where the class name makes a poor variable name.
我认为你可能想到的'规则'更适用于原始类型,以及类名称变量名称较差的类。
For example, if you were dealing with calculating the cost of a particular item in an online store, the following code would not be good form:
例如,如果您正在处理计算在线商店中特定商品的成本,则以下代码将不是良好的形式:
Decimal _decimal = item.BaseCost + item.Tax;
Instead, a more descriptive name would be advised, such as '_total' , or '_cost'.
相反,建议使用更具描述性的名称,例如'_total'或'_cost'。
#22
The only issue with this sort of thing I've found is if you want the same name for a private member and also a public property.
我发现这种事情的唯一问题是,如果你想为私人会员和公共财产提供相同的名称。
If these differ only in case, it'll work fine in case-sensitive languages such as C#, but not in VB.NET.
如果它们的区别仅在于大小写,它在C#等区分大小写的语言中可以正常工作,但在VB.NET中则不行。
So, for instance, in VB, I'd write
所以,例如,在VB中,我会写
Private _name As String
but
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property
I'd do the same in C#, so that translation from one to the other is painless. It also makes it a bit less error-prone, since it's very easy to mis-read, or indeed mis-type words that differ only by case.
我会在C#中做同样的事情,所以从一个到另一个的翻译是无痛的。它也使它更容易出错,因为它很容易被误读,或者确实是错误输入只有大小写不同的单词。
#23
Not immoral, but if your best name for your variable is the name of the type, something wrong or you just making a proof of concept or something like that. For me a variable name must refer to the meaning in the business context and not to the programming language. It will be more difficult to understand the code.
不是不道德的,但如果你的变量的最佳名称是类型的名称,错误的东西,或者你只是做出概念证明或类似的东西。对我来说,变量名必须引用业务环境中的含义而不是编程语言。理解代码会更加困难。
#24
I often use Person person = new Person()
myself. Commonly used in Java/C#.
我经常使用Person person = new Person()。常用于Java / C#。
Although I ended up wondering yesterday why
虽然我最后想知道为什么
private enum DataType {NEW, OLD}
doesn't work in C#...
在C#中不起作用...
Especially seeing how you can use String
, string
, Double
, double
,... at will in C#.
特别是看看如何在C#中随意使用String,string,Double,double,...
#25
Person person = new Person()
is fine in my book.
在我的书中很好。
Wheh it becomes horrible is when you have:
可怕的是,当你有:
string Person;
string person;
Very easy to mix up the 2.
非常容易混淆2。
#26
What has been expressed to me, other then not meeting our Coding Standards, is avoiding adding confusion when someone else is reading my code. I, personally, see no problem with it, as long as the meaning is clear.
除了满足我们的编码标准之外,我所表达的是避免在其他人阅读我的代码时引起混淆。我个人认为没有问题,只要意思清楚。
As for CLR types (int,string, etc.) you can use either String or string (etc.) to declare the type, so I would avoid using something like
对于CLR类型(int,string等),你可以使用String或string(等)来声明类型,所以我会避免使用像
int Int = 0;
string String = "hi there";
#27
Making capitalization the only difference is dangerous...keep doing this for a big project and I guarantee you'll run into bizarre errors you can't seem to locate.
将资本化作为唯一的区别是危险的...继续为一个大项目做这个,我保证你会遇到你似乎无法找到的奇怪错误。
fastPerson/slowPerson like above are fine...they're descriptive and differentiated from the variable type name...but come on man, calling an int "Int" would be plain lazy.
像上面这样的fastPerson / slowPerson很好......它们是描述性的,并且与变量类型名称有区别......但是来吧,调用int“Int”将是非常懒惰的。
#28
I would say its never immoral - it really just your base line variable name. If you can't think of a better name, naming it after it's type is a good default.(For complex types only - for built in types its evil) And lots of time there really isn't a better name cause you don't know anything else about the variable. Like with this method
我会说它永远不道德 - 它只是你的基线变量名。如果你想不出一个更好的名字,在它的类型之后命名它是一个很好的默认值。(仅适用于复杂类型 - 内置类型它的邪恶)而且很多时候真的没有一个更好的名字因为你不'我对变量一无所知。喜欢这种方法
void SaveToDatabase(Person person) {...}
About the only thing else you could reasonably call person is person_to_save
or something like that which seems redundant.
关于你可以合理地称之为人的另一件事是person_to_save或类似的东西似乎是多余的。
However in a lot of cases you can improve on the readability of your code by replacing person with a more descriptive name. For example this is less descriptive
但是,在很多情况下,您可以通过使用更具描述性的名称替换人来提高代码的可读性。例如,这不太具描述性
void AddToAccount(Account account, Person person) {...}
than this
void AddToAccount(Account account, Person dependent) {...}
However please, please - pretty please don't put an 'a' or 't' in front of the type name. I.E. aPerson for 'a person' or tPerson for 'the person'. Its overly complicated and doesn't add much if any value. Plus you starts to pollute you scope with a bunch of variables that start with a or t which can minimize the value of intelli-sense.
不过请拜托 - 请不要在类型名称前加上'a'或't'。 I.E. aPerson为'一个人'或tPerson为'这个人'。它过于复杂,并没有增加太多的价值。另外,你开始用一堆以a或t开头的变量来污染你的范围,这些变量可以最小化智能的价值。
#29
I wouldn't say it's horrible. I usually prefix the name of the variable with 'a' in this sort of thing to show that it's a single instance of the type, so I would do
我不会说这太可怕了。我通常在变量的名称前加上'a'来表示这是一个类型的单个实例,所以我会做
Person aPerson = new Person();
It makes the code read more naturally I think.
它让我认为代码读得更自然。
#30
Absolutely nothing wrong with it subject to caveats pointed out by others (summarizing here for convenience): not doing it with primitive types, refactoring the original instance if another instance is added later, not using char-case to differentiate class names, etc.
绝对没有任何问题,但受其他人指出的注意事项(为方便起见):不使用原始类型,如果稍后添加另一个实例则重构原始实例,不使用char-case来区分类名等。
My rule of thumb? Statements in code should read like simple English sentences.
我的经验法则?代码中的语句应该像简单的英语句子一样。
Person person = new Person();
人人=新人();
Employee employee = person.getRole(EMPLOYEE);
员工雇员= person.getRole(EMPLOYEE);
Parent parent = person.getRole(PARENT);
父母= person.getRole(PARENT);
person.getFullName();
employee.getSalary();
parent.getChildren();
parent.getFullName(); // assuming decorator pattern at play
parent.getFullName(); //假设装饰模式在游戏中
if (person.hasRole(EMPLOYEE)) {
if(person.hasRole(EMPLOYEE)){
...
}
And so forth.
等等。
If the variable's scope is limited (the encapsulating method is 10-15 lines, for instance) I might even use 'p' instead of 'person'. Shorter variable names are less of a distraction when trying to hold context in your head. Avoid gratuitous prefixes such as 'a' or (shudder) Hungarian notation and offshoots thereof. (Mind you, I have nothing against such prefixes when used in the appropriate context - C++ / COM / ATL / Win32 API code etc., where it helps to keep assignments / typecasting straight).
如果变量的范围有限(例如,封装方法是10-15行),我甚至可能使用'p'而不是'person'。在尝试保持头脑中的上下文时,较短的变量名称不会分散注意力。避免使用诸如“a”或(颤抖)匈牙利符号及其分支之类的免费前缀。 (请注意,在适当的上下文中使用时,我没有反对这些前缀 - C ++ / COM / ATL / Win32 API代码等,它有助于保持分配/类型转换直接)。
My two(!) bits :-)
我的两个(!)位:-)