我使用的变量名与它的类型只有大小写不同,这是不道德的吗?

例如,以下面这段代码为例:

var person = new Person();

或者对你们来说,勾股线人:

person = Person()

我经常被告知这有多糟糕,但是我还没有看到这两行代码不道德的例子。对我来说,人就是人,给它起另一个名字就是浪费时间。我想在语法突显之前这会是件大事。但是现在,很容易区分类型名和变量名。见鬼,在 SO 上甚至很容易看出区别。

还是我遗漏了什么?如果是这样,那么如果您能够提供一个导致问题的代码示例,将会很有帮助。

4725 次浏览

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.

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.

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.

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.

Immoral... No. More difficult than it has to be for a refactoring,.. Yes.

Try "_person"

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.

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. :)

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

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

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.

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.

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 :)

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'.

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.

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#.

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.

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.

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.

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.

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";

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.

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).

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.

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.

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.

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 .

If someone says that is evil, ask them if this is better:

var abc = new Person();

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.

Only if you're programming in VB6. In that case, what you're doing is illegal, but not immoral.

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.

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 :-)

Not only is it OK but reasonable.

Microsoft has even suggested similarly (this may come as a surprise to some people) that properties be named the same as their types. I know this isn't the same thing but it may open up your thinking.

http://msdn.microsoft.com/en-us/library/fzcth91k(VS.71).aspx

No it not bad to name it different e.g.

Person clerk = new Person();
Person manager = new Person();

What is bad is making up meaningless names as below :

Person xyz = new Person();