Is it good practice to trim the setter?

I am doing a code review and I noticed a code like this:

@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 cropping inside the setter, I feel that this is not the clearest solution - what is the common practice with this problem?

+8
java
source share
4 answers

If you know that you always need to trim the value, this script will avoid code duplication, Ie in front of your kit you need to constantly trim and worry about where you missed the trim. In my opinion, it is good practice to have it in the setter

+3
source share

Using setters to do anything else, but set the value transparently, violates the principle of separation of problems: with this design, you constantly interlace the configuration problem with care about pruning. This is all wonderful and attractive if you are 100% sure that you will never, for the whole life of your program, have as a single use case where you want to install without cropping. As soon as you need it, the failure mode of this project is rather pathetic: you will have the usual set method, which is actually β€œspecial”, and it will have to add another setWithoutTrimming method, exactly the opposite of any sane assumption for a new programmer.

More generally, my choice is to use pure public fields (Hibernate supports them, as well as Spring, Jackson, etc.), which makes the semantics of determining their dead clarity. If I have another problem, such as cropping, then I use an explicit call to the static method (pure function), which does the necessary conversion. This leads to a clear and obvious design without any WAT, such as "why does the getter return a different value from what I just set?".

+1
source share

I feel that while the method is documented, the logic inside it is beautiful.

At the end of the day, you don’t want to end up loading places in the code where you are cropping before calling the installer.

If you later decide that you no longer need to trim the line, you only have one change.

In the end, the encapsulation point is the placement of the data and the behavior of that data in the same place.

0
source share

This code is ok. The reason why setters are preferable to public values ​​is because you can enter any logic into them without violating the class interface. I have only one note, if you trim the string in the setter, then you should always trim it in the getter. In your current case, you have a problem:

  • get empty value
  • install it
  • and then try again

The first and last get will be different. This is possible if the table can be populated from an external object.

0
source share

All Articles