views:

2052

answers:

13

From what I gather as a Java beginner, when accessing instance members, the "this" keyword may apparently be used, but is not mandatory.

I wonder whether there is any official recommendation of sorts of a style guide (though I was unable to find anything in the actual Java style guide).

How do people usually do this, or is there maybe even something like a consensus in the Java community?

+6  A: 

Using the keyword this helps improve the readability and understandability of your code, and signals to anyone else who may read your code, present or future, your intentions. Plus, it's probably proper OO style to reference the object by name, especially if it is this.

Edit: In reply to Robin's comment, when I want an object to call its own method, then yes, I do use the this keyword as well. I feel that this practice alleviates any ambiguity.

eleven81
Does that mean you use 'this' for method calls as well?
Robin
I deliberately don't, because it's potentially misleading. You may end up calling an overridden method, but preceding the call with this' suggests that the same object will receive the call.
Brian Agnew
I agree. I was kind of subtly addressing the line about "proper OO style", since if it applies to the member it should also apply to methods.
Robin
Putting "this" in front of a method does nothing for readability. this or no this resolves to the same method, that is, this object's method, overridden or not, static or not.
Steve Kuo
+3  A: 

Don't forget, you have to use it in some circumstances:

private int x;

public void setX(int x) {
  this.x = x;
}

otherwise there'll be confusion as to which x you're talking about and you'll set the parameter x to itself (for this reason I use final on my method parameters)

Brian Agnew
true, but a better solution (IMHO) in this case would be to different variable names which would also make the code easier to read.
Steve Haigh
I find exactly the opposite. I use the style Brian notes to make the code easier to read. (And I use final on my method parameters as well)
CoverosGene
If you rely on a naming convention, and then someone 'helpfully' renames your variables, then stuff will stop working. I use final more and more to restrict inadvertent behaviour, and it's something I evangelise about (it pained me to write the above code!)
Brian Agnew
Shadowing variables is never a good idea. The parameter should have a different name than the field.
TofuBeer
That's an opinion which is not universally shared.
CoverosGene
i find a style of "setX(int init_x) { x = init_x }" works well. the init in the parameter name conveys intent.
Aaron F.
+5  A: 

Style guides vary from project to project. In Java I used to favour using "this." instead of using a naming convention like "m_". Now I work in C# and use "this." all the time, and we enforce it on our code base with StyleCop. I personally find code slightly easier to read this way.

Having said that I would say it is more important to be consistent with your project's guidlines if you are working with others.

Steve Haigh
+1 for consistency.
Robin
A: 

If you take a look at Eclipse's Source > Clean Up... functionality, you will find that adding this. to every reference to an instance variable is actually one of things you could choose to do. It's considered code clean up, so it's gotta be good :)

No really, it does make the code more readable. I recommend using this when possible.

Peter Perháč
+1  A: 

I use "this" when there is an argument to the method with the same name. This usually happens when auto-generating constructors and setters (in Eclipse) as the Java standard does not ask to have "", "m" or "m" before private members names.

Here is an example:

public class Example {

    private String name;

    public Example(String name) {
     this.name = name;
    }

    public String getName() {
     return name;
    }

    public void setName(String name) {
     this.name = name;
    }

    public String greet() {
     return "Hello " + name;
    }
}

You can also check the Java code conventions

David Rabinowitz
+5  A: 

Since modern IDEs colour code member fields, the unnecessary use of this is background noise to the intent you're trying to convey in the code.

Unless necessary, like when there's a naming conflict, don't do it.

Allain Lalonde
I find that I don't notice the difference in colouring when I am concentrating on the text.
Tom Hawtin - tackline
True, enough. But you're free to make them as annoying as you like.
Allain Lalonde
Then again, with modern IDEs if you do type "this." you often get code completion tools to help lazy developers find the variable/method name.
Steve Haigh
I'll admit, I use that sometimes, but then I'll promptly delete the "this." portion of the statement.
Allain Lalonde
You don't even need to type 'this' for that, although it will limit the options for you.
Robin
+2  A: 

I tend to consider the choice a highly context sensitive one. Where it helps make the code more understandable, I include it. Where it doesn't, I don't.

That being said, I tend to write my methods to be short enough that I rarely consider it to be helpful... and I tend to write static methods whenever possible (I'm a functional programmer at heart).

RHSeeger
+1 for short methods
Allain Lalonde
+4  A: 

I don't ever remember seeing a codebase where this is used consistently where it is unnecessary. If it's obvious where the variable is declared, there doesn't seem much point in adding extra noise.

Tom Hawtin - tackline
+2  A: 

No. I find Java verbose enough as it is and do not feel the need to add additional unnecessary characters unless there is viable need.

This above preference, and the combination of modern IDE context coloring along with variable naming conventions, works for my little world. :)

Stu Thompson
A: 

There are certain coding techniques that require this in Java, beyond cosmetic preference. Here are two examples that I use fairly often.

First, if you want to use method chaining within a class so that the method returns the same type as the type it belongs to, you should use this.'

public class MyBuilder  {
  private long id;
  private String name;

  public MyBuilder id(long id) {
    this.id = id;
    return this;
  }

  public MyBuilder name(String name) {
    this.name = name;
    return this;
  }

  public AnotherType build() {
    // business logic that consumes instance variables to build AnotherType
  }
}

The other case is the Visitor pattern

public interface Visitor<V extends Visitable> {
   public void visit(V visitable);
}

public interface Vistable<V extends Visitor> {
   public void accept(V visitor);
}

And its implementations will say:

public class ConcreteVisitable implements Visitable<ConcreteVisitor> {
  public void accept(ConcreteVisitor visitor) {
    // grant access to ConcreteVisitable's state to the Visitor
    visitor.visit(this);
  } 
}

public class ConcreteVisitor implements Visitor<ConcreteVisitable> {
  public void visit(ConcreteVisitable target) {
     // business logic that operates on the state of ConcreteVisitable
  }
}

Notice that ConcreteVisitable uses this to allow its visitor's access to its state. I'm using generics on the interfaces so that I can enforce a 1-1 mapping between ConcreteVisitors and ConcreteVisitables and so that ConcreteVisitors have particular knowledge of their targets without needing a class cast..

Alan
A: 

Personally I am a member of the "only when necessary" group, and I'm also not a member of the "funky names for private members to avoid using 'this'" collective.

i.e.,

private String m_Name;
public String getName() { return m_Name; }
public void setName(String name) { m_Name = name; }

is undesirable in my book - if only because IDEs can find it hard to find the matching getter and setter for a private member and thus if you use the "generate getters and setters" option you can end up with faffed up duplicate getters and setters. I also think names like m_Foo are ugly and pointless in a language like Java. Even worse to me is _foo or __foo type naming. I think Java needs syntactic sugar for getters and setters to clean this issue up.

However in non-setters I do not use this. to prefix member names, the IDE can colour and style these members perfectly adequately (when configured, annoyingly the Eclipse defaults aren't that great, I sometimes long for the lovely syntax colouring that Emacs or VIM provided).

JeeBee
+1  A: 

I never use "this." unless I have to. I find that the 5 characters are a distraction, and a waste of typing time.

I also enable the Checkstyle check for hiding fields which means that you cannot have a local variable with the same name as a field. On the other hand Checkstyle has another check to make sure that you use "this.", so clearly other people do not feel the same way I do about it being noisy and a waste.

What I do to make sure that I don't get conused about what is a field and what is a local variable is:

  • never have two names in the same scope with the same name (Checkstyle ensures that)
  • always declare all of the variables and fields at the top of their block (this ensures that I always look at the top of the blocks when searching for a name)
  • keep methods short (most methods are less than 10 lines, if you follow the "rule" above and you cannot spot the local variable, then you need better glasses :-)
  • I also never declare and initialize a variable at the same time, which means it is less noise where the variables are declared, and thus makes it easier to find.

So I search for variables like this:

public class Foo
{
    private final int a;

    public void bar(final int b)
    {
        final int c;

        c = 7;

        for(int d; d < 10; d++)
        {
            final int e;

            if(d < c)
            {
                int f;

                f = car(d);
                e = f * 42;
            }
            else
            {
                e = 42;
            }
        }
    }
}

If I am in the "else" and I am looking for "a" I do the following:

  • look at the top of the else, did not find any variables.
  • look where "e" is, did not find "a".
  • look where "d" is, did not find "a".
  • look where "c" is, did not find "a".
  • look where "b" is, did not find "a".
  • look where "a" is, clearly found "a".

You might look at that and say "this.a" would be faster, but remember you likely are aware of the code that you are working on (you should be!) so you should have an idea of what the variables are already. Also given the other "rules" I make use of I could skip ahead to the last check and see if it is an instance variable right away.

TofuBeer
A: 

I find using 'this' as messy. I use m_ for and instance variable, s_ for a static variable and p_ for a parameter. I have found these make the code easier to follow. YMMV

Javamann