Is it clearer to always use "this" or only when necessary? [duplicate]
Possible Duplicate:
Java - when to use 'this' keyword
Some developers like to always use "this" when referring to an object's methods and properties, even when it isn't needed. Here's a really simple example:
public class Foo {
private String id;
public Foo() {
this.id = "123456789";
}
}
Is it clearer to always use "this" or only when it is necessary?开发者_开发知识库 Are there any cases in which you should always use it?
It make no difference in the generated code. So use is up to company development guidelines or personal preference.
It can help identify what is a member variable and what is not, it also help to use this-> as the ide or editor can do better code completion (depending on the age of the editor).
This is purely a matter of personal preference and style. Some programmers find that always using an explicit this
aids readability, while other find that it clutters code without adding value.
Many company coding guidelines will specify whether this
should be used or not, so you should endeavour to stick to the guideline in this case. If the project you are working on is for personal use, then it's really up to your own preference to use explicit this
or not.
In answer to "Are there any cases where you should always use this
?" You should use it when it is needed to avoid ambiguity, for example if there is another variable with the same name in scope. In particular, it is very common in java for constructor parameters to have the same names as a class's fields, which are then assigned with this.field = field
.
I've never worked somewhere that people use a superfluous this in C++ or Java. If you keep your functions short, it's not difficult to tell what's a member variable and what isn't, and often doesn't matter much anyway. For me, it falls under the don't repeat yourself principle, the same reason we have namespaces, so we don't need ReallyReallyLongVariableNamesUnlessWeLikeThem.
I'm guessing it's a style carryover from languages where it's mandatory, like perl and python.
精彩评论