Should the RequireThis check in Checkstyle be enabled?
I would definitely turn it off. Using this.foo()
is non-idiomatic Java, and should therefore only be used when necessary, to signal that something special is going on in the code. For example, in a setter:
void setFoo(int foo) {this.foo = foo;}
When I read code that makes gratuitous use of this, I generally mark it up to a programmer without a firm grasp on object-oriented programming. Largely because I have generally seen that style of code from programmers that don't understand that this isn't required everywhere.
I'm frankly surprised to see this as a rule in CheckStyle's library.
The RequireThis rule does have a valid use in that it can prevent a possible bug in methods and constructors when it applies to fields. The code below is almost certainly a bug:
void setSomething(String something) {
something = something;
}
Code like this will compile but will do nothing except reassign the value of the method parameter to itself. It is more likely that the author intended to do this:
void setSomething(String something) {
this.something = something;
}
This is a typo that could happen and is worth checking for as it may help to prevent hard to debug problems if the code fails because this.something
is not set much later in the program.
The checkstyle settings allow you to keep this useful check for fields while omitting the largely unnecessary check for methods by configuring the rule like this:
<module name="RequireThis">
<property name="checkMethods" value="false"/>
</module>
When it comes to methods this rule has no real effect because calling this.getMeSomething()
or just getMeSomething()
has no effect on Java's method resolution. Calling this.getSomethingStatic()
still works when the method is static this is not an error, it is only a warning in various IDEs and static analysis tools.
Calling with "this." does not stop the invocation from calling an overridden method in a subclass, since this refers to "this object" not "this class". It should stop you from mistaking a static method for an instance method though.
To be honest, that doesn't sound like a particularly common problem, I personally wouldn't think it was worth the trade-off.