Am I immoral for using a variable name that differs from its type only by case?

Language AgnosticCoding StyleNaming ConventionsVariable Names

Language Agnostic Problem Overview


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.

Language Agnostic Solutions


Solution 1 - Language Agnostic

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.

Solution 2 - Language Agnostic

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.

Solution 3 - Language Agnostic

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

Solution 4 - Language Agnostic

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

var abc = new Person();

Solution 5 - Language Agnostic

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.

Solution 6 - Language Agnostic

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.

Solution 7 - Language Agnostic

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.

Solution 8 - Language Agnostic

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.

Solution 9 - Language Agnostic

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.

Solution 10 - Language Agnostic

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.

Solution 11 - Language Agnostic

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.

Solution 12 - Language Agnostic

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.

Solution 13 - Language Agnostic

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.

Solution 14 - Language Agnostic

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

Solution 15 - Language Agnostic

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.

Solution 16 - Language Agnostic

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

Solution 17 - Language Agnostic

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 .

Solution 18 - Language Agnostic

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

Solution 19 - Language Agnostic

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

Solution 20 - Language Agnostic

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

Solution 21 - Language Agnostic

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

Solution 22 - Language Agnostic

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.

Solution 23 - Language Agnostic

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

Solution 24 - Language Agnostic

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.

Solution 25 - Language Agnostic

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.

Solution 26 - Language Agnostic

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

Solution 27 - Language Agnostic

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.

Solution 28 - Language Agnostic

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.

Solution 29 - Language Agnostic

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.

Solution 30 - Language Agnostic

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

Solution 31 - Language Agnostic

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

Solution 32 - Language Agnostic

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

Solution 33 - Language Agnostic

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

Try "_person"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason BakerView Question on Stackoverflow
Solution 1 - Language AgnosticAndrew HareView Answer on Stackoverflow
Solution 2 - Language AgnosticJoshBerkeView Answer on Stackoverflow
Solution 3 - Language AgnosticBill the LizardView Answer on Stackoverflow
Solution 4 - Language AgnosticChrisView Answer on Stackoverflow
Solution 5 - Language AgnosticPEZView Answer on Stackoverflow
Solution 6 - Language AgnosticMike DunlaveyView Answer on Stackoverflow
Solution 7 - Language AgnosticTim AlmondView Answer on Stackoverflow
Solution 8 - Language AgnosticMark BrittinghamView Answer on Stackoverflow
Solution 9 - Language AgnosticRobin DayView Answer on Stackoverflow
Solution 10 - Language AgnosticMitch WheatView Answer on Stackoverflow
Solution 11 - Language AgnosticklozovinView Answer on Stackoverflow
Solution 12 - Language AgnosticRob WilliamsView Answer on Stackoverflow
Solution 13 - Language AgnosticDavid ThornleyView Answer on Stackoverflow
Solution 14 - Language AgnosticGerrie SchenckView Answer on Stackoverflow
Solution 15 - Language AgnosticJoachim SauerView Answer on Stackoverflow
Solution 16 - Language AgnosticStewart RobinsonView Answer on Stackoverflow
Solution 17 - Language Agnosticuser8599View Answer on Stackoverflow
Solution 18 - Language AgnosticbrianeggeView Answer on Stackoverflow
Solution 19 - Language AgnosticFrederik GheyselsView Answer on Stackoverflow
Solution 20 - Language AgnosticmafuView Answer on Stackoverflow
Solution 21 - Language AgnosticJay SView Answer on Stackoverflow
Solution 22 - Language AgnosticChrisAView Answer on Stackoverflow
Solution 23 - Language AgnosticCarraView Answer on Stackoverflow
Solution 24 - Language AgnosticJoão CintraView Answer on Stackoverflow
Solution 25 - Language AgnosticJohnno NolanView Answer on Stackoverflow
Solution 26 - Language AgnosticMuad'DibView Answer on Stackoverflow
Solution 27 - Language AgnosticalexwoodView Answer on Stackoverflow
Solution 28 - Language AgnosticJoshuaView Answer on Stackoverflow
Solution 29 - Language AgnosticRob KView Answer on Stackoverflow
Solution 30 - Language Agnosticalan-pView Answer on Stackoverflow
Solution 31 - Language AgnosticSpragueView Answer on Stackoverflow
Solution 32 - Language AgnosticfastcodejavaView Answer on Stackoverflow
Solution 33 - Language AgnosticStingyJackView Answer on Stackoverflow