Using "this" in Java vs Short Parameter Names

What do you prefer and why?

public void setPresenter(Presenter presenter) { this.presenter = presenter; } public void setPresenter(Presenter p) { presenter = p; } 
+7
source share
4 answers

I prefer this notation, at least in constructors and complex setter methods, where you have a few arguments.

  • You do not need to come up with two variable names for each field.
  • From the "external" one can see what the argument represents.
  • This is a really standard approach.

In the particular case of the setter, I really have no opinion, since the method name is understandable enough, and the implementation is one purpose.

+10
source

I prefer this - this class illustrates why

 class foo { int value; int otherValue; void setValue(int i) { value = i; } void setOtherValue(int i) { otherValue = i; } // uhh what? void setBoth(int i, int j) { // which one should be first? oh, you guessed and got it wrong? tooooo bad! } } 
+3
source

We use full words for instance variables and TLA for methods, so we will have:

 public void setPresenter(Presenter prs) { presenter=prs; } 

This allows for fairly understandable names, avoids misappropriation errors caused by missing this , and clearly distinguishes long-term / large-scale identifiers from short-term / narrow areas.

+2
source

I prefer not to use this , since (by accident) leaving it (mostly using it) can lead to obscuring errors when using longer methods.

However, you must use a reasonable name for the parameters. Therefore, I prefer to use prefixes for parameters and local variables:

 public void setPresenter(Presenter pPresenter) { presenter = pPresenter; //pXxxx stands for 'parameter' Presenter tPresenter = pPresenter; //tXxxx stands for 'temporary' or local } 
+1
source

All Articles