Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to have trim in setter?

Tags:

java

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?

like image 540
zibi Avatar asked Nov 08 '13 09:11

zibi


2 Answers

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

like image 111
Arsen Alexanyan Avatar answered Nov 14 '22 14:11

Arsen Alexanyan


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?".

like image 25
Marko Topolnik Avatar answered Nov 14 '22 14:11

Marko Topolnik