3 ms·
Getters and setters: 1. Are only conventions. Nobody's forcing you to use them. 2. Simplify refactoring. 3. Are a necessary layer of abstraction any time tha
by vkou 6y ago
Getters and setters:
1. Are only conventions. Nobody's forcing you to use them.
2. Simplify refactoring.
3. Are a necessary layer of abstraction any time that 'setting' a value requires updating a related value.
#1 and #2 are only a manner of taste and implementation-specific use cases of tooling built on top of a language. #3, however, is absolutely necessary, to avoid entire categories of business logic errors.
Just imagine if updating a string's value required you to also manually update the string's length. How many string-length related bugs do you think that kind of adventure will result in a typical program?
- lmm 6y agoThe very concept that you can change a string's value or length is an absurdity. A string is a value. If you want a different string, form one.
- vkou 6y agoI don't say that a string has to be mutable, I am saying that when you assign a value to a string variable, such as during its first (and let's say 'only') initialization, it would be absolutely insane to also have to set the string's length. Arguing against setters is like arguing that String s = "foo"; must also be accompanied with s.length = 3; The two operations make zero sense to be done separately - doing so is just a minefield of bugs. The purpose of a setter is to combine similar inseparable operations together. A trivial pass-through setter obviously provides ~zero value, but it also carries with it ~zero cost. Any compiler worth its salt will optimize its invocation away.
- lmm 6y ago> I am saying that when you assign a value to a string variable, such as during its first (and let's say 'only') initialization, it would be absolutely insane to also have to set the string's length. You should have a constructor/factory for strings that will form/instantiate the string in a valid state, with its value matching its length. That's not the same thing as a setter that mutates the string in-place.