24

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

36 accepted

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.

23

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.

12

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.

9

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.

7

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

6

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!

4

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.

4

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.

3

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.

3

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.

3

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.

1

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.

1

From Code Complete --pick a style that you and your team are comfortable with. No style gives more advantage than the one that most team members feel comfortable with. And then stick with it and close the debate so that more time is spent in construction rather than a debate on best practices. That said, the same argument does not apply to style choices that promote code breaks. I do not think the use of this falls under this category though.

Personally I prefer to get rid of every useless prefix, qualifier, suffix etc. and invest such gains in improving the name quality instead. But that is highly debatable so I will not say more. I have been part of many teams. Some followed this and some no this but m_ conventions. But I didn't feel any loss in productivity under either regime.

1

When using Eclipse, typing this (ie this.instance_variable) conveniently pops up Eclipse's auto complete. This can make coding a little faster by a) filling in a function or variable name for you and b) remind you of how you implemented your class (ie variable names used, function signatures).

0

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

0

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.

0

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;
}
0

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

0

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!

0

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.

0

I realize this question is old, but I have to chip in. In my opinion, naming conventions are a crutch that reflects limited syntax coloring capabilities in older IDE:s. Fortunately, this is history. (Standard disclaimer applies: always adapt your code style to any existing style of code you have to touch.)