Getter-Setter和私有变量 [英] Getter-Setter and private variables
本文介绍了Getter-Setter和私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我可以通过getter返回的引用更改私有变量的值,那么它是否绕过setter方法?它是否会破坏getter-setter和私有变量的目的
If I can change the value of private variable through getter-returned reference then isn't it bypassing the setter method? Doesn't it defeat the purpose of getter-setter and private variables
public class Test{
private Dimension cannotBeChanged;
public Test(int height, int width)
{
if(height!=3)
cannotBeChanged.height = height;
if(width!=3)
cannotBeChanged.width = width;
}
public Dimension getDimension()
{
return cannotBeChanged;
}
public void setDimension(int height, int width)
{
if(height!=3)
cannotBeChanged.height = height;
if(width!=3)
cannotBeChanged.width = width;
}
public static void main(String [] args)
{
Test testOne = new Test(5,5);
Dimension testSecond = testOne.getDimension();
testSecond.height = 3; //Changed height and width to unwanted values
testSecond.width= 3;
}
推荐答案
是的,确实如此。我在清洁代码一书的getter和setter中得出以下结论;如果你真的接受它就可以使用它。
Yes, It does. I have the following conclusion in getters and setters from the Clean Code book; you can use it if you really accept it.
- 非常邪恶:公共领域。
- 有点邪恶:吸气剂和二传手不需要它们。
- 好:只有在真正需要的地方才有吸气剂和制定者 - 使
类型暴露更大的行为恰好使用其状态
而不仅仅是将类型视为由其他类型操纵的
状态的存储库。
- Very evil: public fields.
- Somewhat evil: Getters and setters where they're not required.
- Good: Getters and setters only where they're really required - make the type expose "larger" behaviour which happens to use its state, rather than just treating the type as a repository of state to be manipulated by other types.
这篇关于Getter-Setter和私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文