Is it always clearer to use "this" or only if necessary?

Possible duplicate:
Java - when to use the keyword 'this'

Some developers always use "this" when referring to object methods and properties, even if they are not needed. Here is a really simple example:

public class Foo { private String id; public Foo() { this.id = "123456789"; } 

}

Is it always clearer to use "this" or only when necessary? Are there any cases when you should always use it?

+4
source share
3 answers

This has nothing to do with the generated code. Therefore, use depends on company recommendations or personal preferences.

This can help determine what is a member variable and what is not, also helps to use this->, since an ideal or editor can improve code execution (depending on the age of the editor).

+5
source

It is solely a matter of personal preference and style. Some programmers find that they always use the explicit readability of this , while others find it cluttering up the code without adding a value.

Most corporate coding guides indicate whether to use this or not, so you should try to follow the recommendation. If the project you are working on is for personal use, then it really depends on your preference for using this explicit or not.

In response to "Are there times when you should always use this ?" You should use it when necessary to avoid ambiguity, for example, if there is another variable with the same name in the scope. In particular, in java the constructor parameters very often use the same names as the fields of the class, which are then assigned using this.field = field .

+2
source

I have never worked somewhere that people use redundant this in C ++ or Java. If you keep your functions short, it's easy to say what a member variable is and what is not, and often it doesn't really matter. For me, this falls under the Do Not Repeat Yourself principle, for the same reason we have namespaces, so we don't need ReallyReallyLongVariableNamesUnlessWeLikeThem.

I assume this is a style transfer from languages โ€‹โ€‹where it is required, like perl and python.

+1
source

All Articles