After a recent code review I noticed a lot of code similar to the following:
this.createAUser();
or
if (this.isValidProfile()) {
Our coding standards allow for using this with fields to make the distinction clear:
private int count; pubic void setCount(int count) { this.count = count }
We adopted The Elements of Java Style for our coding style guide about 2.5 years ago, but this is a case I’d never spent much time thinking about. I find it a lot clearer to write something like:
createAUser()
or
if (isValidProfile()) {
I always assumed this was a well understood convention, but after spending some Googling around I found nothing specifically on idioms with using this with methods.
I think the best evidence in favor of not using the this keyword is with Martin Fowler’s Extract Method pattern. You often create small methods by doing a simple extract of a code fragment on a method that’s getting a little long. And Martin’s example suggests calling the extracted methods with:
printBanner(); printDetails(getOutstanding())
not:
this.printBanner(); this.printDetails(this.getOutstanding())
For me it all comes down to better readability, but we’ll probably have a short meeting with some of the senior developers to toss it around and come to a final decision. If we hadn’t been doing code reviews on a regular basis we might have never addressed this issue.