ajsie
ajsie

Reputation: 79756

using this to call a instance variable?

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

Upvotes: 7

Views: 1257

Answers (6)

chaqke
chaqke

Reputation: 1617

I'm a fan of using the language features when programming in a language. Thus, I would recommend against using "this." on an instance variable unless required to distinguish it from a method parameter that is colliding on the same name.

Upvotes: 0

Joe Phillips
Joe Phillips

Reputation: 51150

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

Upvotes: 5

Ondra Žižka
Ondra Žižka

Reputation: 46836

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

Upvotes: 1

Ravi Vanapalli
Ravi Vanapalli

Reputation: 9942

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

Upvotes: 0

Carl Manaster
Carl Manaster

Reputation: 40356

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.

Upvotes: 2

Andy White
Andy White

Reputation: 88385

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.

Upvotes: 4

Related Questions