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

前端 未结 14 663
既然无缘
既然无缘 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条回答
  •  旧时难觅i
    2020-12-29 02:21

    Yes. It's a bad practice.

    Why?

    When the value is set (in a constructor or setter method), it should be validated, not when a getter method is called. Creating a private validate* method for this is also a good idea.

    private boolean validateThisValue(String a) {
         return this.myValue != null && !this.myValue.isEmpty();
    }
    
    public void setThisValue(String a) {
        if (validateThisValue(a)) {
            this.myValue = a;
        } 
        else {
            // do something else
            // in this example will be
            this.myValue = "N/A";
        }
    }
    

    And, in the getter method, never ever change the state of the object. I have worked on some projects, and the getter often must be made const: "this method cannot change internal state".

    At least, if you do not want to complicate things, in the getter method, you should return "N/A" rather than change internal state and set myValue to "N/A".

提交回复
热议问题