可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
For instance, take this piece of code:
var person = new Person();
or for you 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.
Or is there something I'm missing? If so, it would be helpful if you could provide an example of code that causes problems.
回答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
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.
回答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.
Person person = 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.
回答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.
回答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.
回答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
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.
回答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".)
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.
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.
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)
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.
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.
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").
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.
Microsoft .NET recommends lowerCamelCase for parameters and non-public fields and UpperCamelCase (aka "Pascal Style") for other types of identifiers.[20]
Python recommends UpperCamelCase for class names.[21]
The NIEM registry requires that XML Data Elements use UpperCamelCase and XML Attributes use 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").
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).
回答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[]
and deduplicatedUsers[]
. If you move the deduplication to a utility method, you can call the method Utils.dedup(array)
, and you can call the deduplicated array deduplicatedArray
or just result
.
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.
See Larry Wall's principle of "Local Ambiguity is OK" - 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
.
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.
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.
回答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. :)
回答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 :)
回答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'.
回答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.
So, for instance, in VB, I'd write
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.
回答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#.
Although I ended up wondering yesterday why
private enum DataType {NEW, OLD}
doesn't work in C#...
Especially seeing how you can use String
, string
, Double
, double
,... at will in C#.
回答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.
回答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
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.
回答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.
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.
回答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
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.
My rule of thumb? Statements in code should read like simple English sentences.
Person person = new Person();
Employee employee = person.getRole(EMPLOYEE);
Parent parent = person.getRole(PARENT);
person.getFullName();
employee.getSalary();
parent.getChildren();
parent.getFullName(); // assuming decorator pattern at play
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).
My two(!) bits :-)