代码之家  ›  专栏  ›  技术社区  ›  Jarryd

我应该在构造函数中使用getter和setter吗?

  •  3
  • Jarryd  · 技术社区  · 7 年前

    初始化类时,在构造函数中使用getter和setter函数是否是一种良好的做法?

    或者直接设置变量是一种好的做法,因为构造函数可以被视为一种变数?

    3 回复  |  直到 7 年前
        1
  •  12
  •   rghome    5 年前

    您不应该从构造函数调用getter和setter。

    如果您只是从同一个类中获取一个字段,那么调用getter也是一个坏主意。如果它是在超类中声明的,您可以证明它是正确的;如果需要从子类中的超类获取数据,则必须调用getter(除非它受到保护)。如果在构造期间需要将数据从子类传递到超类,则应将其作为参数传递。但这是一个不同于您所描述的用例,并且子类可能不会有您自己的字段对应于getter。

    如果您有任何“特殊”初始化代码,请将其放在单独的私有方法中,并分别从构造函数和setter调用它。

        2
  •  2
  •   KameeCoding    7 年前

    • 如果您想在设计类时考虑继承,那么答案是否定的,如果您使用init方法,那么它也不能使用getter/setter或任何可以重写的方法。 直接引用有效Java第二版:

    类还必须遵守一些限制才能允许 遗产 构造函数不能调用可重写的方法, 直接或间接 . 如果违反此规则,程序将失败 取决于子类构造函数执行的任何初始化,

        3
  •  1
  •   fender0ne    7 年前

    在我看来,当构造函数定义类时,我可以使用setter检查参数和/或将它们初始化为某些值。在我有计算变量的情况下,我也可以使用getter,但是我应该非常小心语句的顺序(不推荐使用容易出错的语句)。

    class Point {
      constructor (x, y) {
        this.x = x.x || x // invokes the setter
        this.y = x.y || y
      }
      toString () {
        return `The point is (${this.x}, ${this.y})` // invokes the getters
      }
      set x (newX) { // I think it should be better use 'newX' as a parameter than 'x'
        if (newX > 100) {
          console.log(`The x (${newX}) value must be < 100, `, 'x set to 0')
          this._x = 0 // if we use 'this.x' here, we will get an error (stack overflow)
          return
        }
        this._x = newX
      }
      get x () { // no one but the getter and setter should know '_x' exists
        return this._x // it has to be coherent with the setter
      }
      set y (newY) {
        if (newY > 100) {
          console.log(`The y (${newY}) value must be < 100, `, 'y set to 0')
          this._y = 0
          return
        }
        this._y = newY
      }
      get y () {
        return this._y
      }
    }
    
        4
  •  0
  •   Shawn Ge    7 年前

    不,拥有访问器和变异器的目的是能够从同一个包中的另一个类访问私有字段。

    从技术上讲,您可以这样做,但是从构造函数中变异变量会破坏初始化的目的。访问变量只需为获取其内容添加额外的步骤。