Is it bad practice to have my getter method change the stored value?

前端 未结 14 711
既然无缘
既然无缘 2020-12-29 02:08

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

Version 1:

 public String getMyValue(){
     return this.myValue
 }
         


        
14条回答
  •  半阙折子戏
    2020-12-29 02:29

    In my opinion, unless you are doing lazy-loading (which you are not in that case), getters should not change the value. So I would either:

    Put the change in the setter

    public void setMyValue(String value) {
        if(value == null || value.isEmpty()){
            this.myValue = "N/A";
        } else {
            this.myValue = value;
        }
    }
    

    Or make the getter return a default value if value not set properly:

    public String getMyValue() {
        if(this.myvalue == null || this.myvalue.isEmpty()){
            return "N/A";
        }    
        return this.myValue;
    }
    

    In the case of lazy-loading, where I would say that changing your members in a getter is fine, you would do something like:

    public String getMyValue() {
        if (this.myvalue == null) {
            this.myvalue = loadMyValue();
        }    
        return this.myValue;
    }
    

提交回复
热议问题