Is it bad practice to have my getter method change

2019-02-03 21:25发布

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;
 }

14条回答
闹够了就滚
2楼-- · 2019-02-03 21:55

Do what ever you like. After all getters and setters are just another public methods. You could use any other names.

But if you use frameworks like Spring, you are bound to use those standard names and you should never put your custom codes inside them.

查看更多
何必那么认真
3楼-- · 2019-02-03 22:00

I usually define a specific getter.

Never alter original getter:

 public String getMyValue(){
     return this.myValue
 }

And create an specific getter:

public String getMyValueFormatted(){

    if(this.myvalue == null || this.myvalue.isEmpty()){
       return "N/A";
    }else{
       return this.myValue;
    }
 }
查看更多
登录 后发表回答