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; }
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.
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.
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.
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.
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"
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With