tags:

views:

57

answers:

5

Should you use "this.variablename" or just "variablename" to reference a member variable in a method?

+3  A: 

You can use whichever you want in most cases. If your method parameter has the same name then you'll need to use this to distinguish the instance variable. Be consistent!

Joe Philllips
Or a local variable (less common). If you have a local class, then it is a mess.
Tom Hawtin - tackline
+2  A: 

You can do either, it's just a matter of taste, but I've seen a lot of Java code use "this." because the arguments to the method are named the same as the member field a lot of times.

You could argue that using "this." also helps readability, because you immediately know it's a member, but you could also argue that "this." hurts readability, because it's just an extraneous word.

Andy White
but since if your parameter is the same word and you have to use this, then probably it's best to stick with it for the sake of convention:)
weng
@noname - If your parameter name and instance name are the same, then you should be choosing better names for your variables. This helps readability much more than the 'this'.
Robin
+2  A: 

I only use this. in two circumstances:

  1. To disambiguate between the field and a local of the same name, for example in a setter;
  2. When my method has a that parameter, because this and that make for nice readable code.
Carl Manaster
oh, im new to java, and haven't reached "that" yet. nice to know in advance what i will encounter in my book:)
weng
You probably won't find it in the book - it's just a nice parameter name to use when working with another object of the same class. Like, say, a Point class might have the method distanceTo(Point that). Then subtracting "this.x - that.x" sounds nicer to me than just "x - that.x".
Carl Manaster
@Carl - Wouldn't 'dest' or 'destination' be a better name?
Robin
@Robin - I find 'that' very natural, very English-like. Typically for code where this and that are - I guess - symmetric; where it doesn't really matter which was called and which was the argument. Try it in one of your such routines, read it out loud, and see what you think. In the case of distanceTo(), obviously, it's symmetric, and since the name of 'this' isn't 'source' - well, I like 'that'.
Carl Manaster
A: 

Just the variable name is ok & to use the parameter variable use "this".

Ravia
+1  A: 

Use this. - it helps other programmers to visually identify the usage of member fields, and makes refactoring easier (e.g. when considering moving of a method to another class).

Ondra Žižka