Reputation: 49097
I am reading the Java Code Conventions PDF and I noticed this:
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:
int count;
...
func() {
if (condition) {
int count;
... }
... }
It is nothing new and I frequently find myself writing such code. How do you solve such cases? Of course you can say "find a better name", but that is not always easy. Are there any conventions on adding something in front or back of the higher level name?
Upvotes: 1
Views: 237
Reputation: 106498
You can use scope-specific variable naming conventions to reduce confusion.
String[] names;
public void populateNames(String[] theNames) {
names = theNames;
}
Also, you can explicitly state which scoped variable you want by use of the this
keyword.
int count = 0;
public void func() {
int count = 0;
if (condition) {
this.count++; // increment the class-scope count variable
} else {
count++; // increment the local scope variable
}
}
In general, just don't reuse your variable names. It confuses those that read your code, and makes debugging a bit harder.
Upvotes: 2
Reputation: 328855
I have seen this coding style used in a library:
_variable
locVariable
parVariable
But I personally think it clutters the code.
Any good IDE will use a colour code that makes a clear difference between a local variable and a class member.
Upvotes: 0
Reputation: 3822
If you're only dealing with method variable declarations, you can use the this
keyword to refer to the instance variable as in the following example:
public class Foo {
private int id;
public void setId(int id) {
this.id = id;
}
}
Here, this.id
refers to the instance variable, whereas id
refers to the parameter passed in to the setter.
I know you said that you don't want to hear suggestions of using better variable names, but I do think the only situation you should really have duplicated names are when you're preparing to set a new value for an ivar, or have just read an ivar. Even then, it's often more readable to use names with a bit more meaning, so for example if you only need a variable that is of the same time as barr
temporarily, name it tmpBarr
or something similar.
Upvotes: 0
Reputation: 23972
Top level variables have more "detailed" names that lower ones. For example:
class A{
private int mVegetablesCount;
public void foo(){
int count;
if(true){
int cnt;
if(true)
int c;
}
}
}
Just as variant. Also, it's good idea to name your class fields specificaly. In my example field named fith prefix "m".
Upvotes: 0
Reputation: 10539
int count;
count = 1;
is not the same as
int count;
this.count = 1;
So if you work with local variable, you just don't user "this."
Upvotes: 0