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.
I use it all the time for temporary object references. I would avoid it like the plague for primitive data types.
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.
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 themunnamedPerson
or something similar.Calling it simply
person
forgoes a big chance to make your code self-documenting.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 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
It makes the code read more naturally I think.
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 prefixperson
with meaningful adjectives likeotherwise just
is fine with me.