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.
The general idea is to never put logic in a getter/setter at all. It should just get or set a field.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
In Java accessors are used to get the value of a private field and mutators are used to set the value of a private field. Accessors are also known as getters and mutators are also known as setters.
Setters cannot return values. While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.
Your case is the very reason for using setters and getters. If you weren't allowed to have logic in a setter, then you might as well access the fields directly!
It is probably not the best practice, however sometimes the life is stronger than best practices.
Probably better approach is to remove field containsDigit
and move the logic you added to setter into isContainsDigit()
:
public class Message {
private final static Pattern d = Pattern.compile("\\d");
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean isContainsDigit() {
return text == null ? false : d.matcher(text).find();
}
}
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