开发者

Using "this" in Java vs Short Parameter Names

Which do you prefer and why?

public开发者_StackOverflow中文版 void setPresenter(Presenter presenter) {
    this.presenter = presenter;
}

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


I prefer the this-notation, at least in constructors, and compound setter methods, where you have multiple arguments.

  • You don't have to come up with two variable names for each field.
  • It is clear from the "outside", what the argument represents.
  • It is really a standard approach.

In the particular case of a setter, I don't really have an opinion, since the method name is explanatory enough, and the implementation is a single assignment.


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!

    }


}


We use full words for instance variables and TLAs for methods, so ours would have:

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

That allows reasonably clear names, avoids misassignment bugs caused by an omitted this and clearly distinguishes long-term/wide-scope identifiers from short-term/narrow-scope ones.


I prefer not to use this since (accidentially) leaving it out (while mostly using it) could lead to shadowing bugs on longer methods.

However, you should use a sensible name for the parameters. That's why 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜