One of the built-in Checkstyle checks is RequireThis, which will go off whenever you don’t prepend this. to local field or method invocations. For example,
public final class ExampleClass {
public String getMeSomething() {
return "Something";
}
public String getMeSomethingElse() {
//will violate Checkstyle; should be this.getMeSomething()
return getMeSomething() + " else";
}
}
I’m struggling with whether this check is justified. In the above example, the ExampleClass is final, which should guarantee that the “right” version of getMeSomething should be invoked. Additionally, there seem to be instances where you might want subclasses to override default behavior, in which case requiring “this” is the wrong behavior.
Finally, it seems like overly defensive coding behavior that only clutters up the source and makes it more difficult to see what is actually going on.
So before I suggest to my architect that this is a bad check to enable, I’m wondering if anyone else has enabled this check? Have you caught a critical bug as a result of a missing this?
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:
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:
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.somethingis 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:
When it comes to methods this rule has no real effect because calling
this.getMeSomething()or justgetMeSomething()has no effect on Java’s method resolution. Callingthis.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.