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

33

95

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.

Lentiginous answered 20/1, 2009 at 13:8 Comment(5)
I've always wondered about this. Nice question!Snodgrass
Calling a Person person is just cruel. What's wrong with "bob"?Nemato
Let's not forget before var there was the zen beauty of Person person = new Person();Malamut
@Jamie are you calling static typing zen-like?Empiric
I would like to go even one level deeper into this question: Is it indisputably wrong to do Person Person=new Person(); for this matter? As stated in The Question, we live in times of such incredible syntax highlighting and context recognition that my compiler never complained on me doing just that. I just love my variables CamelCased - why then shouldn't I (in situations where Person Person is a general and only instantiation of the class and no conflict is present nor possible)?Runnymede
D
94

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.

Dogoodism answered 20/1, 2009 at 13:8 Comment(5)
"What is the reasoning of those telling you this is bad?" - Dunno. That's why I started this topic. :-)Lentiginous
Clearly you've never had to come into someone else's code. I know that when I'm called upon to research some newly discovered bug in several-years-old code by a programmer who's long since left the company - anything that gets in the way of ramping me up is time not fixing the problem. If one of those obstacles is trying to figure out what's an instance and what's a class just because a programmer couldn't be bothered to say "var currentPerson = New Person();" then that is useless, wasted time. ...and when your customers are waiting for a fix, time is of the essence.Diskin
@Diskin - You caught me! I knew that coding in a vacuum would rear its ugly head sooner or later :) Seriously though - I find it hard to believe that you get tripped up by being unable to discern between types and their instances based on this naming convention.Dogoodism
@Diskin -- that should be the problem for the code analysis tool. Also, that's why there is the convention that types start with uppercase letter in Python.Lineate
Why not just use a "my" prefix? myPersonBathypelagic
T
69

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.

Terrenceterrene answered 20/1, 2009 at 13:8 Comment(5)
"What is wrong would be if you have two types Person and person then that is very very wrong." - This makes total sense to me.Lentiginous
If your building an API VB wouldn't be able to handle the code since it's case insensitive.Terrenceterrene
Hey, in the case of an API you're bothered about public method names or properties, not variable names, 'cause the latter aren't going to be exposed to the client code. As for Jason's question, I too use this naming all the time. Absolutely nothing wrong with it.Durr
Exactly my point Frederick why having two types which differ only base case is a bad idea;-)Terrenceterrene
Even if it's not wrong, it makes the code harder to read. Readability matters too.Basinet
R
45

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
Receive answered 20/1, 2009 at 13:8 Comment(4)
If there really was no semantic meaning I could give a primitive I would use i or s, apart from loop indices I cant't think of any other such scenario.Sympathetic
I would recommend against using i, especially if you're writing code with a loop. i is almost universally regarded as a loop variable name.Lentiginous
Agreed. A single letter variable name screams "I'm temporary." Loop indices should be i, j, k, any others should be a, b, c, x, y, z, or any other letter that can't be mistaken for something else, like l and o.Receive
bravo! 42 is just too much. :)Balinese
B
18

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

var abc = new Person();
Bangkok answered 20/1, 2009 at 13:8 Comment(1)
@Chris: exactly! Or better yet: var temp = new Person(); (Disclaimer: I know there really are places for one time use temporary variables, but as often as not when I see this in someone's code, the author simply never got back around to giving the var an appropriate name and it may as well be "abc".)Doyledoyley
T
15

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.

Tic answered 20/1, 2009 at 13:8 Comment(0)
S
9

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.

Snide answered 20/1, 2009 at 13:8 Comment(2)
Alternatively, if the moral decisions we can make are of such insignificance, we're cursed. I'm not sure I want my funeral eulogy to concentrate on my coding style. I'd like at least a passing mention to my being a part of a family.Shofar
@David: Right again. With my first grandkid on the way, I suppose it's trite, but I care what kind of a world we're handing down.Snide
I
8

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.

Isiahisiahi answered 20/1, 2009 at 13:8 Comment(0)
S
6

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.

Selma answered 20/1, 2009 at 13:8 Comment(0)
A
6

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.

Aweigh answered 20/1, 2009 at 13:8 Comment(0)
S
3

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.

Shofar answered 20/1, 2009 at 13:8 Comment(2)
Hi again David. I can't remember if you are the one who edited one of my postings because I had written "pollish", or was it "polish", when I meant to rub something until it shines? Oh well, I'm still not sure which is right :-)Snide
I don't think I made any such edit, so it was probably somebody else. BTW, it's "polish".Shofar
C
3

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.

Chartism answered 20/1, 2009 at 13:8 Comment(0)
D
3

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.

Dhyana answered 20/1, 2009 at 13:8 Comment(0)
L
3

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.

Lilt answered 20/1, 2009 at 13:8 Comment(0)
F
2

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

Forbear answered 20/1, 2009 at 13:8 Comment(0)
P
2

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 .

Pember answered 20/1, 2009 at 13:8 Comment(0)
S
2

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

Smtih answered 20/1, 2009 at 13:8 Comment(0)
R
2

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.

Regalia answered 20/1, 2009 at 13:8 Comment(2)
Call it anonymous! :)) var anonymous = new Person(); Or even better: var you_know_who = new Person(); :))Fennell
@Vadim Ferderer: var he_who_must_not_be_named = new Person();? :-)Recurved
H
2

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()
Hydrocarbon answered 20/1, 2009 at 13:8 Comment(4)
That would be worse, in my opinion. It's harder to read and it provides no additional information whatsoever.Regalia
Yeah but at least the name is different from the class name, which is what they want obviously.Hydrocarbon
That would be following the letters of the law, but definitely not the spirit.Regalia
+1, I use thePerson for parameters and myPerson for locals that I am managing.Byelection
N
1

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.

Nervine answered 20/1, 2009 at 13:8 Comment(1)
I agree with the last paragraph. I don't see any reason to add extraneous characters just to avoid a minor style issue.Lentiginous
P
1

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.

Pentapody answered 20/1, 2009 at 13:8 Comment(0)
I
1

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";
Ilan answered 20/1, 2009 at 13:8 Comment(0)
W
1
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.

Wily answered 20/1, 2009 at 13:8 Comment(0)
F
1

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.

Forefinger answered 20/1, 2009 at 13:8 Comment(0)
A
1

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

Abran answered 20/1, 2009 at 13:8 Comment(1)
enum only supports byte, sbyte, short, ushort, int, uint, long, ulong. i.e. non fractional numeric value typesPhonsa
W
1

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.

Wenzel answered 20/1, 2009 at 13:8 Comment(2)
The only thing that I dislike about this approach is that variables prefixed with a single underscore tend to be associated with private members of a class. But I suppose that the general approach is decent.Lentiginous
Yep, this is what I'm illustrating here. Defining a local variable, such as 'Dim person as New Person' would be fine. Very (very) occasionally with the VB compiler, there is an ambiguity, and the normal reassuring auto-capitalisation doesn't happen. It's a good visual cue that all is not well.Wenzel
P
1

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

Portmanteau answered 20/1, 2009 at 13:8 Comment(0)
D
1

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

Dabber answered 20/1, 2009 at 13:8 Comment(0)
R
1

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

Rout answered 20/1, 2009 at 13:8 Comment(0)
P
0

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(); 
Provo answered 20/1, 2009 at 13:8 Comment(0)
J
0

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

Jereme answered 20/1, 2009 at 13:8 Comment(0)
A
0

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

Anthill answered 20/1, 2009 at 13:8 Comment(0)
A
0

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.

Aphonic answered 20/1, 2009 at 13:8 Comment(0)
S
-4

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

Try "_person"

Strive answered 20/1, 2009 at 13:8 Comment(7)
I answered the question with a legitimate response. Can someone explain why the - vote?Strive
I don't know as I didn't downvote. Often the _ prefix is used on member variables so using it as a local var may be upsetting folks. Who knows.Nemato
Perhaps you need an explanation as to why it's more difficult for refactoring. And I've seen a lot of people who don't like "_".Kassel
I dont like people who name the variable the same as the type, especially in VB.NET, but I aint pickin on thier preference.Strive
I don't know. I save downvotes for things that are actually offensive. Otherwise they're just a bit like zinging people for the fun of it.Snide
I disagree with your repsonse, but I don't know why people downvote without explanation.Macdonell
Thats fine, but the question was "am I immoral". Which I answered. Ask a stupid question... etc etc.Strive

© 2022 - 2024 — McMap. All rights reserved.