views:

406

answers:

8

(For those who read my previous question, this is the same teacher and the same project.)

My teacher 'inspected' my code for a web application project and provided some suggestions. One of the suggestions was to use the this keyword even in this situation:

private String getUsername() {
    return username;
}

So if I follow his advice, that would become:

private String getUsername() {
    return this.username;
}

I asked him why and he told me that there is another usage for the this keyword other than for clearing up ambiguities. A quick googling returned no results for another usage of the this keyword. Even the Java tutorial from Sun mentioned no other usages that would fit in this situation.

A: 

There is no other usage of the 'this' except for calling another constructor of the same class.

Qualifying access to member variables - even if not needed - is considered best-practice by some developers (I don't). The main point is that it is possible to change the semantics of an assignment without changing that line:

class Foo {

  String foo;

  void foo() {
    // a lot of code
    foo = "something"
  }

}

May be changed by simply doing the following:

  void foo() {
    String foo;
    // a lot of code
    foo = "something"
  }

So it's mostly about maintenance and readability - for the price of verbosity.

sfussenegger
+3  A: 

You use it to chain constructors as well:

public class Foo
{
    private final String name;

    public Foo()
    {
        this("Fred");
    }

    public Foo(string name)
    {
        this.name = name;
    }
}

(For chaining to a superclass constructor, use super(...).)

Additionally, there are some weird times where you can use it from an inner class to specify exactly which member you're after. I don't remember the exact syntax, fortunately - I don't need to use it often.

Jon Skeet
Yes, I also know about that. But what other usage could my teacher be telling me in the given example (getter method)?
Ramon Marco Navarro
Well your wording of what the teacher said didn't mention it being another use *within a getter method*. What did he actually say? Personally I don't use `this` redundantly like your teacher is suggesting - I don't think it adds to readability anyway.
Jon Skeet
He said that I should use the this keyword even within a getter method.
Ramon Marco Navarro
@Ramon: Yes, but that's not the same as him saying that the *other* uses of "this" were within getter methods.
Jon Skeet
+1  A: 

Some people think it is good practice to always use the keyword this for class fields. This can be useful in the following situation:

class MyClass {
 private int x = 0;

 public void DoSomething(int x) {
  int privateFieldValue = this.x; // use field of our class
 }
}
DreamWalker
That's the disambiguation use that the question already mentions.
Joachim Sauer
I agree it's useful to to use 'this' disambiguate between fields and parameters, but I don't believe it makes sense to use 'this' all the time even when there is no ambiguity. Can anyone else offer any opinions on whether or not this behaviour is 'good practice'? Is the consensus different between Java and C# programmers? (I'm Java by the way)
Alex Spurling
I prefer either to use 'this' throughout the method or not at all. And I don't normally declare a local variable with the same name as a field unless it's a parameter to a constructor or setter (where it will be assigned to a field with the same name and type.)
finnw
+8  A: 

this also allows you access to the surrounding class instance and its members from within a nested class, e.g.

public class OuterClass
{
    private class InnerClass
    {
        public OuterClass getOuter()
        {
            return OuterClass.this;
        }
    }
}
Michael Borgwardt
That's the usage I was thinking about in my answer. I couldn't remember it - but I'm not sure whether I should actually thank you for reminding me. Blech. I hate inner class syntax.
Jon Skeet
+1  A: 

Always accessing member variables using this. is a coding convention in some places. The idea is probably that it's similar to naming conventions ("All field names must start with an underscore _") but without the ugly name-mangling. (Other places have exactly the opposite convention: avoiding this. unless absolutely necessary).

Personally I don't see any real reason to do it, since all tools you use to access your code should be able to color/style-code each variable/field to make the distinction.

Your grand-dads text-editor is not able to show the difference between accessing a local variable and a field. But that's not a good reason for hard-coding it redundantly in your code.

Joachim Sauer
Many consider prepending fields with "this" a bad practice.
Steve Kuo
+1  A: 

An very important one that hasn't been mentionned, is the use of this for method chaining used in fluent APIs. In this design pattern, all methods return this, regardless of what they do, allowing you to so stuff like:

dog.setColor("black").setSize("tall").makeDangerous().bark();

using an API constructed, so:

public Dog setColor(String c) {
    color=c;
    return this;
    }
JRL
+1  A: 

Also, you can return this to chain method calls - e.g. in Builder pattern.

class CustomerBuilder
{
    private String firstName = "Default";
    private String lastName = "Default";

    public CustomerBuilder setFirstName(String firstName)
    {
        this.firstName = firstName;
        return this;
    }

    public CustomerBuilder setLastName(String lastName)
    {
        this. lastName = lastName;
        return this;
    }

    public Customer build()
    {
        /* ... do some actions to build a Customer object ... */
    }
}

Then, you can use this builder like this:

Customer customer = new CustomerBuilder().setFirstName("John").setLastName("Smith").build();
Shooshpanchick
-1. for copying JRL's answer.
finnw
@finnw: The times are close; they may have done the same answer at nearly the same time, each without seeing the other.
Software Monkey
This is exactly what happened :( There should be a notification before posting like "new responses were added while you were editing" - I've seen that on some forums.
Shooshpanchick
A: 

Using the this keyword will also trigger a warning from the compiler if someone comes along and decides to change the username member to a static variable on you. If you don't use this, the compiler will just play along like everything is cool. And username changing to be static could very well be a bug. So you probably want the warning. And if it isn't a bug, you should change the code that uses username to treat it as if it is static to avoid future bugs / misunderstandings in the code. That way, if someone comes along and changes it back you'll get a new warning.

So, if nothing else, in the context of a getter, it can also trigger compiler warnings when other things change on you. And that is a Good Thing.

dbingham