Consider a Message object in Java that stores some text.
public class Message {
private String text;
private boolean containsDigit;
public Message() {
//constructor
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean isContainsDigit() {
return containsDigit;
}
}
This is a persisted object.
I have no problem with data being set in the constructors but the Message's text field can be set after the object is created and when the text is set, the containsDigit field should also be query-able thereafter. The obvious way to do this is in the setter:
public void setText(String text) {
// presume existence of method to check for digit
if(text.containsDigit())
this.containsDigit = true;
this.text = text;
}
But does this result in any "best practice" alarms bells going off due to having logic within a setter method?
Would anyone suggest an alternative implementation?
EDIT
I should probably add that the containsDigit
field is required because the object is persisted so the containsDigit
field can be queried subsequently.
Also, in an application using the Spring/Hibernate engine, this setter is constantly called when re-reading/writing the object so was wondering about the practicality/efficiency of this also.