46

I come from languages like Python or Javascript (and others that are less object-oriented) and I am trying to improve my working knowledge of Java, which I know only in a superficial way.

Is it considered a bad practice to always prepend this to the current instance attributes? It feels more natural to me to write

...
private String foo;

public void printFoo() {
    System.out.println(this.foo);
}
...

than

...
private String foo;

public void printFoo() {
    System.out.println(foo);
}
...

as it helps me to distinguish instance attributes from local variables.

Of course in a language like Javascript it makes more sense to always use this, since one can have more function nesting, hence local variables coming from larger scopes. In Java, as far as I understand, no nesting like this is possible (except for inner classes), so probably it is not a big issue.

In any case, I would prefer to use this. Would it feel weird and not idiomatic?

4
  • We use a tool to stadardise that in our company. The tool rerite code with our without this depending on the company policy. So everbody codes how they like and code is formatted the right way at commit time.
    – deadalnix
    Commented Oct 10, 2011 at 13:37
  • 2
    "since one can have more function nesting, hence local variables coming from larger scopes." Also, the fact that "this" isn't actually one of the places an unqualified variable can come from in a function in JS.
    – Random832
    Commented Oct 10, 2011 at 13:38
  • 2
    I prefix all instance variables with underscore so I can easily tell the difference between local and instance variables without using this.
    – WuHoUnited
    Commented Oct 10, 2011 at 14:57
  • 6
    In C# StyleCop wants you to put this. when referring to member variables, methods, etc. I like that, I agree with this rule. I think it is better than naming something with an underscore at the beginning. I would follow the same rule if I were coding in java.
    – Job
    Commented Dec 18, 2011 at 20:24

8 Answers 8

44

In most IDEs, you can simply mouseover the variable if you want to know. In addition, really, if you're working in an instance method, you should really know all the variables involved. If you have too many, or their names clash, then you need to refactor.

It's really quite redundant.

7
  • 7
    Also: a sane IDE should make fields and local variables/parameters visually distinct. For example in Eclipse (by default) fields are blue, while local variables are black. Commented Oct 10, 2011 at 13:10
  • 1
    @Joachim Nice point, Eclipse can even color parameters and local variables differently if the user wishes (this is not by default however).
    – Eric-Karl
    Commented Oct 10, 2011 at 13:37
  • 5
    Though I agree, when coming across other developers' code (and while being unfamiliar at first glance) I find this. a lot more helpful. This is also probably because I don't have an IDE that color-codes local/object variables differently. Commented Oct 10, 2011 at 23:58
  • 3
    +1 for (paraphrase) "refactor if you need to use this to deduce that it's a member". Just what I wanted to point out. Commented Oct 11, 2011 at 0:02
  • 1
    I don't find it makes it harder to read, and in return, the code remains readable in editors that have less sophisticated syntax highlighting that doesn't distinguish between fields and locals. I've always had the opinion that you should strive for your code to be easily readable in the most basic of text editor, and if it isn't, there should be a good reason for it.
    – Kevin
    Commented Jan 31, 2017 at 16:21
33

I prefer to use this. It makes it easier to read code in various editors that color local and instance variables in the same way. It also makes it easier to read the code on a printed page during something like a code review. It's also a fairly strong reminder as to the scope of the variable to other developers.

However, there are arguments against this. In modern IDEs, you can find out the scope of a variable by hovering over it or viewing it in a tree-like structure. You can also change the color and/or font face of variables depending on their scope (even in such a way that, when printed, it's evident what the scope of the variable is).

I believe that ChrisF's last sentence is dead on: be consistent in your usage.

1
  • 8
    "It's also a fairly strong reminder as to the scope of the variable to other developers." - the reason I tend to use and like to see this. in the code. Takes half a second to write and can save long minutes when having to figure out whether the guy before you really meant to use the pascal-case property instead of camel-case local there when he made that last minute burst of changes 20 revisions ago.
    – scrwtp
    Commented Dec 19, 2011 at 1:07
20

One place I consistently use 'this' is setters and or constructors:

public void setFoo(String foo) {
    this.foo = foo;
}

Other than that, I don't feel it is necessary to add it. When reading the body of a method, parameters and locals are right there - and fairly easy to keep track of (even without the IDE help). Also locals and fields tend to be of different nature (object state vs transient storage or parameter).

If there is any confusion about what's a variable and what's a field, it probably means a method has too many variables/parameters, is too long and too complex, and should be simplified.

If you choose to use 'this' to tag fields, I would recommend to make sure the convention is always strictly followed - it would be really easy to start assuming no 'this' means it's a local and break stuff based on the assumption.

edit: I also end up using this in equals, clone or anything which has a 'that' parameter of the same object type:

public boolean isSame(MyClass that) {
    return this.uuid().equals(that.uuid());
}
1
  • This is a good answer. My practice is to use 'this' when assigning to fields, which means there is no name conflict in setters or constructors.
    – Thomas W
    Commented Mar 21, 2021 at 22:18
11

Is it considered a bad practice to always prepend this to the current instance attributes?

Yes - by some, no - by others.

I like and use this keyword in my projects in Java and C#. One can argue that IDE will always highlight parameters and fields by different color however we don't always work in IDE - we have to do a lot of merges/diffs/some quick changes in a notepad/check some code snippets in e-mail. It's way easier for me to spot from the first look where instance's state is changed - for example, to review some possible concurrency issues.

8

It's debatable.

Taking C# as an analogy as it has a very similar syntax and structure to Java we find that C# StyleCop has a default rule that insists you add this, but ReSharper has a default rule that says that the this is redundant (which it is) and can be removed.

So if you are using one tool you'll add them but if you use another you'll remove them. If you are using both tools then you'll have to chose and disable one of the rules.

However, what the rules do mean is that you are consistent in your usage - which is probably the most important thing.

7

I think that if you need to use this, you either have a method that is too long, or a class that is trying to do too much, or both.

Methods should never be more than a few lines of code long, use one or two local variables, determining what is what becomes easy; even with only the 3 lines context of most diff tools. If your methods are too long and your classes have too many responsabilities (often meaning too many fields), the solution is to split them instead.

I think that "this" just clutters code. Especially with modern IDEs that will color local parameters/local variables/fields differently.

7

I think you answered your own question with this:

It feels more natural to me to write

... this.foo ...

than

... foo ...

as it helps me to distinguish instance attributes from local variables.

If you are more comfortable using this. while improving your working knowledge with Java, then by all means use the thing (I think it's, in a way, the familiar Python self that you are relating to).

The thing is that, although people will give solid/pertinent arguments about using or not using this., it still sound like a debate, example given:

  • it makes the purpose of the variables clear vs. you should rewrite the code if it's not clear what each variable is;
  • this. is redundant if you spend your entire day in the IDE vs. I perform code reviews and make diffs on different versions using a comparator with no syntax highlighting;
  • not typing this. gains me important milliseconds of productivity vs. I get payed by key pressed and adding this. is like a pay raise :D;
  • etc etc

But bottom line is, that at the end of the day, it still resumes to personal preference and work environment.

6

Normally adding this is unnecessary. I don't think it is bad practice per se, but excessive use of this would probably be considered unusual in most Java code bases that I've seen.

However I find it valuable in a couple of specific situations:

Overriding local parameters - sometimes it is necessary to specify that you want to use an instance variable rather than a parameter / local variable of the same name. This is quite common in constructors, where you want the parameter name to match the internal name of the instance variable it is used to initialise e.g.

class MyObject {
  int value;

  public MyObject(int value) {
    this.value=value;
  }
}

When handling other instances of the same class - I believe it makes the code clearer and more understandable to be explicit which instance of the class you are referring to, e.g.

class MyObject {
  int value;
  ....

  public MyObject add(MyObject other) {
    return new MyObject( this.value + other.value )
  }
}

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .