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

前端 未结 14 659
既然无缘
既然无缘 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:24

    I think it's better to initialize this.myValue = "N/A". And subsequent calls to setMyValue should modify the this.myValue according to your business conditions.
    The getMyValue shouldn't modify in any way this.myValue. If your needs are to return a certain value, you should return that value (like "N/A") and not alter this.myValue . Getters must not modify member's value.

提交回复
热议问题