That is why you use setters, and not reveal the fields of objects for the whole wide world.
Consider a class that contains an integer angle, expected from 0 to 359 inclusive.
If you expose a field, callers can configure it for what they want, and this will violate the contract specified by your API. It can also upset your functionality somewhere down the track because your code is written to accept a specific range for this variable.
With the installer, you can do several things. One of them is to raise an exception by specifying an invalid value, but that would be wrong in my view (for this case). This will probably be more useful if you change the input value to something between 0 and 359, for example:
actualVal = passedValue % 360;
As long as this is indicated in your interface (API), it is completely correct. In fact, even if you do not specify it, you are still free to do whatever you want, because the caller has violated the contract (passing the value out of range). As a rule, I adhere to the rule "sanitize your contribution as soon as possible."
In your particular case, while you indicate that the string is stored in a truncated format, there is no reason for the caller to complain (you have already stated that such a string is unacceptable). It is better in terms of code size (not speed) to do this in the setter, and not on every piece of code that the setter calls. It also ensures that the string is saved as you expect - there is no guarantee that the caller will not accidentally (or purposefully) save the string without trimming.
source share