使用我的getter方法更改存储的值是不好的做法吗? [英] Is it bad practice to have my getter method change the stored value?

查看:162
本文介绍了使用我的getter方法更改存储的值是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



版本1:

  public String getMyValue(){
return this.myValue
}

版本2:

  public String getMyValue(){

if(this.myValue == null || this.myValue.isEmpty()){
this.myValue =N / A;
}

return this.myValue;
}


解决方案

如果您的 getter 方法改变对象的内部状态,这是一个糟糕的做法。



要实现相同的效果, / em> N / A




  • 可能在其他地方(内部)使用,您不需要使用getter方法。所以最后,调用 foo.getMyValue()实际上可以改变 foo 的行为。



或者,从 null 可以在 setter 中执行,即内部值可以设置为N / A if null 已通过。






一般备注:

如果某些API或其他依赖您的代码的实例需要这些状态,我将只添加N / A等状态。如果不是这种情况,您应该依赖于在您的编程语言中可用的标准null类型。


Is it bad practice to change my getter method like version 2 in my class.

Version 1:

 public String getMyValue(){
     return this.myValue
 }

Version 2:

 public String getMyValue(){

    if(this.myValue == null || this.myValue.isEmpty()){
       this.myValue = "N/A";
    }

    return this.myValue;
 }

解决方案

I think it is actually quite a bad practice if your getter methods change the internal state of the object.

To achieve the same I would suggest just returning the "N/A".

  • Generally speaking this internal field might be used in other places (internally) for which you don't need to use the getter method. So in the end, the call to foo.getMyValue() could actually change the behaviour of foo.

Alternatively, the translation from null to "N/A" could be done in the setter, i.e. the internal value could be set to "N/A" if null is passed.


A general remark:
I would only add states such as "N/A" if they are expected by some API or other instance relying on your code. If that is not the case you should rely on the standard null types that are available to you in your programming language.

这篇关于使用我的getter方法更改存储的值是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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