Am I immoral for using a variable name that differ

2020-06-06 07:28发布

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.

30条回答
冷血范
2楼-- · 2020-06-06 08:07

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
查看更多
迷人小祖宗
3楼-- · 2020-06-06 08:08

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.

查看更多
Ridiculous、
4楼-- · 2020-06-06 08:09

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.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-06-06 08: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.

查看更多
一纸荒年 Trace。
6楼-- · 2020-06-06 08:10

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.

查看更多
你好瞎i
7楼-- · 2020-06-06 08:13

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.

查看更多
登录 后发表回答