views:

2573

answers:

18

And... we have another QAW (Quality Assurance War) on our hand.

After reading the more generic "What kind of prefix do you use for member variables?" question, I tried to argue with my QA department about the advantages to always add 'this' before instance (or member) variables in java code. They are not convinced.

I know there is a similar question question, but specific to cocoa.

My arguments for adding 'this' before member variables in java are:

  • there is no sure way to ensure one naming convention for instance variables, whereas 'this' is universal to the language
  • it is easy to do (with IDE like eclipse, and the use of the 'quick fix' mechanism, that IDE can add 'this' automatically throughout the code of a given java source code)
  • it clearly differentiates instance variables and member variables, again without depending on a specific naming convention.

When it comes to java, what is your take on that practice ?


Your answers are very informative and help me to understand why the QA (for code quality) was not convinced.

You are basically saying that it is:

  • a matter of taste
  • a risk of code cluttering (too much 'this' everywhere)
  • a way to resolve some punctual naming conflict, or avoid mutability issue.

I would however argue that:

  • eclipse already alert us whenever a naming override occurs (between a parameter and an instance variable), so this is not actually an issue for us.
  • final keyword is already enforced (findbugs does report every 'final' needed)
  • adding 'this' is an alternative to whatever naming convention you may favor (easily applied automatically).

The net added value of 'this. prefix' would be a clear identification, in a long method, of the usage of instance variables, whatever the quality/complexity of the code is.
... But that seem less important than a 'clear' code, based on the faith that the programmer will actually produced such a "clear-not-too-complex-good-quality" code.

Why not. I do respect all those points of view, and thank you again for giving them here.
If you have other argument for or against using 'this.' before instance variables, feel free to add them ;)

+17  A: 

If a piece of code has enough complexity or name conflicts, then making the code simpler and removing the conflicts would be a better goal than enforcing the use of 'this'. It should be clear without it.

Nerdfest
You sure sound like my QA department ;) Good point though.
VonC
IMHO naming conventions to underline variable scope, type, visibility just clutters the source code w/o adding value; having small readable classes and selfexplanatory methods names are a better way.
Manrico Corazzi
@Manrico CorazziAnd... why are you saying this in a comment ? Write it in an answer ;)
VonC
+8  A: 

I tend to avoid prefixing 'this' when the meaning is unambiguous. I find that it increases the visual noise you need to sift through to find the meaning of the code.

Also, if it's overused, you may find that your brain starts to automatically filter it out of what you see, effectively devaluing any explicitness that it might otherwise have added.

Martin McNulty
+11  A: 

I tend not to use this where it's obvious that variables belong to the object. However, quite often with setters, you see the code:

void setNumerator (int numerator) {
    this->numerator = numerator;
}

which is one place where it's handy.

Where the member functions are large, I use it so I don't have to search at the top of the function/file to see the scope.

paxdiablo
I agree. The time it takes me to type "this." is less than the time it takes me to needlessly think of a new variable name.
Bill the Lizard
That's the only place I use it too. And I don't end up typing that one. Eclipse generated getters and setters use this in the setter.
John Meagher
+3  A: 

I'm not sure why it being easy is an argument for doing it. There's lots of things to do that are easy and bad ideas! :)

I personally don't see the need. I believe it just makes the code more verbose without adding any more "useful" information to it.

Brian Knoblauch
+1  A: 

I tend to avoid "this" keyword. My IDE is configured to tell me if I'm overridding the scope of an internal variable, and generally I access interal member through accessor. Doing so I'm reducing the work when refactoring implied changing the structure of a internal member.

gizmo
A: 

Uh, no, thanks. The only (common) use I see is in constructors, when giving parameters of same name than the fields/member variables.

Now, even for this, there are alternatives:

Classical (Sun way):

Foo(int x, int y) {
  this.x = x;
  this.y = y;
}

Alternative (decorating parameters):

Foo(int _x, int _y) {
  x = _x;
  y = _y;
}

(variant: with suffix, or other decorations)

Another alternative (the solution I chose, and incidently which is used at my work for a large Java code base. Notation comes from Microsoft...):

Foo(int x, int y) 
{
  m_x = x;
  m_y = y;
}

All class member variables are prefixed with m_ It might look too heavy for some people, but at least you know at a glance if a variable is local or a member, and it is a rather nice side effect to group our members (eg. on an overridden class) in debug view of Eclipse...

PhiLho
+2  A: 

I prefer to use a short prefix to denote member variables. In my current company the consensus is to use _ (ie, userName) in previous companies it was m (m_userName).

Using this. or this-> is clearly 100% equivalent.

There is little benefit to mandating a particular coding style - in fact it could be detrimental to morale. There is a huge benefit to encouraging your engineers to write clear, readable, maintainable code, as well as to be tolerant of other people's coding styles, and to want to learn more about the craft.

If you've already got an engineering department that does all of these things, then go ahead and focus on "this." and enforcing the One True Brace Style, otherwise, your time is better spent elsewhere.

plinth
A: 

With IDEs like Eclipse, using "this" would make the code a bit more unreadable.

Before Eclipse came around, the people here used "m_" prefix as a standard. We see it many a times in the legacy code we still have.

Satish Motwani
+2  A: 

I think it's a matter of personal taste, do what works for you or your team.

I know if I opened up a java class and saw "m_" all over the place I would FREAK. but whatever works for you guys.

bpapa
A: 

In my organization our code style is such that all private, non-static member variables are prefixed by an underscore. I like this much better than using "this":

public void setFoo(int foo) {
    _foo = foo;
}
jchilders
As a new programer to your team, I would have no idea what the underscore means. The this keyword, on the other hand, would instancely have meaning. Why flout the actual language itself?
David Medinets
As a new programmer to his team, I would know exactly what that mant, because it's a fairly well known coding convention adopted by *many* teams. I would also know what this.foo meant. I would hate though to have this.foo (member variable) and foo (method variable) only discernible by (cont)
Troy Howard
the this. prefix, because, it makes it far too easy to type foo, meaning method variable, when you meant to type this.foo member variable, and have the compiler pass it right through and introduce a bug. it seems harder to screw up the underscore than to forget the "this.".. IMHO
Troy Howard
+2  A: 

When modifying someone's code, I tend to follow whatever the initial developer did or did not do. Whether that is through this or a member variable prefix. I think the consistency of the code is more important.

My own personal use is to use this when scope issues arise. More often than not, it's only in accessors that I find myself including it.

Sean
Good point on the consistency issue. I should look at this policy from a 'legacy vs. new code' point of view...
VonC
+26  A: 

I hate using prefixes like "m_", so I use "this" a lot. Why create something new (like a prefix standard) when there's already something built into the language? When there's a new person on the project, there's nothing to learn when using "this". Plus, not everyone may end up using the same IDE with the same syntax coloring.

Gary Kephart
I like your reasoning ;) But it seem you may be one of the few to follow this approach...
VonC
This answer does illustrate the pragmatic advantages I try to put forward in my question... but be warned: that "answer" does not reflect the majority of the points of view expressed here ;)
VonC
Although, you should see the comments of http://stackoverflow.com/questions/218123/what-was-the-strangest-coding-standard-rule-that-you-were-forced-to-follow#218138
VonC
A: 

It just clutters up the code with minimal improvements in 'instant recognition' of the scope. I also have not seen the m_ practice since coding C++ years ago. Doesn't seem to be much of a standard for Java coding.

I also find the practice of declaring local variables final to be of no practical value. It is not part of the API, adds clutter, and will be changed at the developers whim if they want to change the variable.

Pretty much the same goes for final for paramaters as well, since they are also little more than local variables as well. Mutability is not an issue as it is a property of the object being passed as the parameter, not the local variable pointing to it. Declaring the parameter final simply keeps one from reassigning it (for objects at least).

Robin
that all "clutter" thing baffles me. I use 'this' and 'final' everywhere, and view it as fundamental. Especially final, which allows me to never reassign it by mistake while coding.
VonC
I do wish tht final were the default and you had to add a keyword for it to be changeable...
TofuBeer
I suppose comments clutter up the code too ;)
sfossen
Depends on the comments. Wow, two comments on a 6 month old answer.
Robin
A: 

I hate using "this." anywhere. Because I use Eclipse, and Eclipse highlights my class' member fields in blue, so I always know which field it is addressing. There is no reason to shadow variable names unless they're very common, and even if you do, highlights applied via the IDE will show you which fields are assigned to your class and which are local variables in a method. Plus, this for methods inside the same class is completely pointless. Consider:

a.doSomething(); doSomethingElse();

Since there is no prefix to a variable in front of doSomethingElse, it HAS to come from the current class! Adding this. in front of a method declaration doesn't help in the slightest here!

MetroidFan2002
" Adding this. in front of a method declaration doesn't help in the slightest here! ": you are absolutely correct. But I do believe that is not the topic of the question. Only member/instance variables are to be considered here.
VonC
And again, if you'd read my response, you'd see that I answered that: "Because I use Eclipse, and Eclipse highlights my class' member fields in blue, so I always know which field it is addressing."
MetroidFan2002
A: 

The only thing I dislike about python is putting "self" everywhere. It's just unnecessary and distracting. I only ever end up using "this" in Java constructors and a occasionally a few other places, and I don't think it's ever confused me or a caused a conflict, so I don't see the problem.

Draemon
+6  A: 

"this." is evil !!! I would like to submit a modification to the Java language specification to treat a scopeless dot as "this.". For example instead of doing

a = this.field;

or

b = _field;

one could do

a = .field;

What do you think?

I was frustrated by heavy JSR submission procedure.

alex
Interesting compromise. I personally find this.aField more readable... but that's just me. And considering the other answers, that is actually just me. Alone ;)
VonC
Still +1 for this proposition
VonC
+2  A: 

To me its about code readability

The only interface we all have with the code the words on the screen.

Having a prefix makes it difficult to read in your head.

What do you say in your head when you see _variable?

do you say underscore variable and ignore the underscore or do you filter out the underscore when you read it and only read variable (if so why have it there at all??)

Using this gives you scope inside your head!

If I open a class, I know my reference point, using the this refers to the variable in this class.

If you think about it in common language would you ever drop the word this in a sentence?

i.e:

does 'this variable' belong to you?

as opposed to

does 'variable' belong to you?

it implies the same but I would argue the first is more eloquent!

Craig Angus
Good point. +1.
VonC
I would shoot myself if I actually translated code into English when reading. Sucks to be you!
methodin
+2  A: 

I realize this is a very old question, and it's unlikely that anyone will ever read this.

It seems worth pointing out though, that the majority of these answers are along the lines of "I like this or that because Eclipse makes it easy". Eclipse won't always be around, and I can tell you from experience that if you habitually tailor your coding practices to a specific IDE or any kind of coding aide, you may regret it at some point.

I also prefer to allow my team to work in whatever IDE they prefer. If they're a Java wizard in vi (or more likely, netbeans), why force them to relearn? New IDEs are changing this philosophy, most notably with UI design, but whenever possible code should be environment agnostic.

Bottom line is, if you code with good practices, the best IDEs will always support what you're doing. If you tailor your practices to the quirks of a specific environment, even if it's really great, the next really great environment may do things differently.

DougW
I am still here. And I read *every* answer to my questions ;) +1 btw.
VonC