Java setters and "this"

I noticed that many people do in Java installations:

1)

public void setX(int x) {
    this.x = x;
}

Personally, I don't like this, and I think it should be something like:

2)

public void setX(int newX) {
    x = newX;
}

Are there any reasons for the former to be better?

Not 1) it’s easier to make a mistake. On several occasions, I tracked code errors that people make:

x = x; 

mistakenly, maybe because they typed quickly and just wanted to remove getters and setters.

+5
source share
8 answers

This is a matter of style. Argument in favor

public void setX(int x) { this.x = x; }

is that you don’t need to think about a new and meaningful name for the input argument, since you already have one.

Choose a style and use it consistently.

+14
source

Reasons for preference this.x = x:

  • this.x = x , Java-.
  • x , .
  • x = newX , , - .
+7

, "" "". .

+4

. , . , IDE / /. , Eclipse Alt + Shift + R, S, , /, OK. , IDE , x = x this.x = x.

this.x = x. Eclipse (, Dali Hibernate Tools) .

x = newX ( ) () " t OO.

+3

, javadoc ..

, this.x = x. , , . , ?

+3

this.x = x;. . IDE this.

+2

, , , . , , , , .

+2

, IDE. , IDE. , IDE .

+1

All Articles