Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;  } 
like image 837
someone Avatar asked Dec 14 '12 09:12

someone


People also ask

Are getter methods bad?

Getter and setter methods (also known as accessors) are dangerous for the same reason that public fields are dangerous: They provide external access to implementation details. What if you need to change the accessed field's type? You also have to change the accessor's return type.

Should you use the getter method also whenever you use the setter method?

Getters and Setters Are Highly Overused All fields should be kept private, but, setters should only be kept private when it makes sense, which makes that object Immutable. Adding an unnecessary getter reveals an internal structure, which is an opportunity for increased coupling.

Should getter methods be private?

The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.

Can we use getter without setter?

If your class is going to be used in the environment where setter is not required (e.g. ORM / dependency injection / serialization frameworks), it should be OK to do not use setter. In this particular case setter does not make much sense since variable is final and set only once.


1 Answers

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.

like image 61
fgysin Avatar answered Sep 19 '22 20:09

fgysin