I'm doing a code review and I noticed such a code:
@Entity
@Table(name = "SOME_TABLE")
public class SomeReportClass {
@Column(name = "REPORT_NUMBER", length = 6, nullable = false)
private String reportNumber;
.....
public String getReportNumber() {
return reportNumber;
}
public void setReportNumber(String reportNumber) {
this.reportNumber = StringUtils.trimToNull(reportNumber);
}
}
Every time I see trimming inside of a setter I feel that its not the clearest solution - what is the general practice with that issue?
If You know that You always need to trim the value this scenario will avoid code duplications, I.e. before your set You have to trim always and worry about where have You missed triming. In my opinion this is a good practice to have it in setter
Using setters to do anything else but transparently set the value violates the principle of the separation of concerns: with this design you have eternally intertwined the setting concern with the trimming concern. This is all great and peachy—as long as you are 100% sure that you will never, for the lifetime of your program, have as much as a single use case where you want the setting without the trimming. Once you do need it, the failure mode of this design is quite pathetic: you'll have a regular set
method which is in fact "special" and be forced to add another setWithoutTrimming
method, exactly the opposite of any sane assumption for a new programmer.
On a more general note, my choice is to use pure public fields (Hibernate supports them, as well as Spring, Jackson, etc.), which makes the semantics of setting them dead clear. If I have another concern, such as trimming, then I use an explicit call to a static method (a pure function) which does the necessary transformation. This leads to clear and obvious design, with no WATs such as "why is the getter returning a different value from what I just set?".
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