从构造函数中调用setter

从构造函数中调用setter

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

问题描述

从构造函数(如果有)调用mutator的pro和con是什么

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

ie:

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

与:

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

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

您有偏好吗? (这不是功课,只是查看我们的编码标准文档,它说在构造函数中设置实例var时始终会调用mutator而我并不总是这样)

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.

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:25