The only case I can think of is for some kinds of refactoring. To create an example, an object may have started out as a collection of static methods that are not very object-oriented:
public static void doItToIt(Foo it) {
if (it.getType().equals("bar")) {
it.setSomeVariable(value);
it.manipulate();
} else {
// do nothing
}
}
... so we decided to get rid of getType()
and make it a subclass relationship, and when refactoring, the thing was copied and pasted so as to make the code cleaner and more object-oriented, necessitating:
public class Bar extends Foo {
private Bar it = this;
private String getType() {
return "bar";
}
public void doItToIt() {
if (it.getType().equals("bar")) {
it.setSomeVariable(value);
it.manipulate();
} else {
// do nothing
}
}
}
If there were only one method like this, it'd be better to use a local variable:
public void doItToIt() {
final Bar it = this;
...
}
but if there are several, using an instance variable would get the code working faster.
It would now be better to go and replace all instances of it
with this
(and get rid of getType()
, and remove the if
, and so forth) but as an intermediate step it's still an improvement, and it might get left in that state if there are (or are thought to be) other, more important things to do.
Another possibility would be copying pseudo-code from something like a specification in which this
has a name in the pseudo-code and you are deliberately attempting to match the pseudo-code structure to make it easy to compare the implementation to the specification. (And, again, if you had multiple methods so using a local variable would lead to repetition.)
But generally speaking, no, having an instance variable that always refers to this
is redundant and thus impedes clarity.