2 ms·
> Getters and Setters also permit you to specify that something can only be retrieved or assigned, but not the other. Only retrieved? `final` and set the fiel
by avgcorrection 5y ago
> Getters and Setters also permit you to specify that something can only be retrieved or assigned, but not the other.
Only retrieved? `final` and set the fields through the constructor.
Sure someone could implement setters-only if they wanted that. Except I’ve never seen it and get/set are always used instead. Just one layer of indirection for no benefit.
- Jtsummers 5y agoThat's not equivalent. You may want a field to be updated by other actions. That is, its value is derived from the other properties of the system. You could recompute those on each request, but that's potentially costly. You could also recreate the entire object with each small field change. That's also very costly. Consider a collection class which has a size field. `final` would be the wrong thing to use. If you expose the size field but make it final, well, it's immutable and your entire collection is either lying or also immutable. If you expose the size field but it's not final, then anything can alter it. Consequently, a getter (the concept of one at least, see C# again for a cleaner approach than what Java did historically) is useful and then when another element of the interface is used (adding or removing elements) the size field can be updated appropriately. The next time it's retrieved, it's correct and you don't need to recompute it. This kind of thing can be a consequence of many other systems, a collection is just sufficiently universally understood that it's a good example of the concept.
- avgcorrection 5y agoA collection is a red herring. A collection uses a “getter” for the size since the size is not something you get/set like in a value object. But then again no one calls it a “getter” (not even Java calls it `getSize()`) since the get/set discussion is about updatable fields, not the inner guts of objects. Has anyone argued against encapsulation? No one has.