从构造函数调用 setter [英] calling setters from a constructor

查看:33
本文介绍了从构造函数调用 setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从构造函数(如果有)调用 mutator 的优点和缺点是什么

What are the pro's and con's of calling out to a mutator from a constructor (if any)

即:

public MyConstructor(int x) {
  this.x = x;
}

对比:

public MyConstructor(int x) {
  setX(x);
}

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

你有偏好吗?(这不是作业,只是看看我们的编码标准文档,它说在构造函数中设置实例变量时总是调用增变器,但我并不总是这样做)

Do you have a preference? (This is not homework, just looking at our coding standards doc where it says to always call out to mutators when setting instance var's in the constructor and I don't always to this)

推荐答案

就我个人而言,我会在大多数情况下直接设置变量.

Personally, I would set the variable directly in most cases.

方法通常期望实例在被调用时完全形成.特别是,从构造函数调用被覆盖的方法会导致难以理解的代码和难以发现的错误.

Methods usually expect that the instance is fully-formed by the time they're called. In particular, calling an overridden method from a constructor is a recipe for hard-to-understand code and hard-to-spot bugs.

话虽如此,无论如何我经常尝试使类不可变,在这种情况下,不仅没有设置器,而且您必须从构造函数(或变量初始值设定项)设置最终变量无论如何:)

Having said that, I often try to make classes immutable anyway, in which case not only is there no setter, but you have to set the final variable from the constructor (or a variable initializer) anyway :)

属性有逻辑的地方,setter 逻辑通常是验证,有时会改变对观察者的传播.我通常希望在方法开始时显式检查构造函数参数,并且无论如何您都不会希望在完全创建实例之前发生任何更改传播.

Where properties have logic, setter logic is usually validation and sometimes change propagation to observers. I'd usually expect the constructor parameters to be checked explicitly at the start of the method, and you wouldn't want any change propagation to occur before an instance is fully created anyway.

这篇关于从构造函数调用 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆