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"
.
getter
functions will never change the object's value. You can perform this check in other function and set the value of it in asetter
function. Just to have a clear code. – Otolithmyvalue
in the if is spelt with lower case 'v', twice. Is it intentional? – AdonisIs it bad practice for a getter to change an object's member's value?
, as it is it sounds like you are asking whether it's bad for a getter's internal implementation to change, to which I believe the answer is no, it's ok to change it. – Fulsome