是否更好地使用getter方法或在覆盖toString时直接访问私有字段? [英] Is it better use getter methods or to access private fields directly when overriding toString?
问题描述
我已经看过两种方法,但从未听说过任何一种方式比其他方式更受欢迎。
I've seen both approaches used but have never heard that one way is preferred over the other for any particular reason.
public String toString() {
return this.field1 + " " + this.field2;
}
与
public String toString() {
return getField1() + " " + getField2();
}
我在我的例子中使用String连接来保持代码简洁。
I used String concatenation in my example to keep the code brief.
推荐答案
如果你拥有它们,请使用getters!
Use getters, if you have them!
也许,有一天你改变代码,以便getter不仅会返回字段值,而且会做更多的事情或以不同的方式创建结果。然后你会更高兴你一直使用getter。
Maybe, one day you change the code so that a getter will not only return the fields value but do something more or create the result in a different way. Then you'll be more then happy that you used getters consistently.
但是像往常一样,我的建议有一些例外 - 你对toString()方法有什么期望?如果你允许覆盖getter方法,你是否希望它使用classes字段或者 - 或者覆盖 - getter方法的结果。
But as usual, there are excemptions from my advice - what do you expect from the toString() method if you allow overriding of the getter methods, do you want it use the classes fields or the result of the - maybe override - getter method.
所以,像往常一样,它取决于,但除非我有充分的理由直接访问这些字段,否则我会使用getter。
So, as usual, it depends, but I'd use getters unless I have a good reason to access the fields directly.
这篇关于是否更好地使用getter方法或在覆盖toString时直接访问私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!