pengu1nxWhy are attributes often private, but then have a getter and setter?
Swayzea design pattern that emerged out of the need to often validate values before assigning them
Swayzealso you can change complex internal logic without changing your classes contract
NeXeNnever reach into private members, we all learned that in kindergarten
Swayzehes asking WHY they're private to begin with
Swayze(you CANT reach into private members)
NeXeNbut my joke is funnier
pengu1nxI don't really understand the second note. What exactly do you mean by contract and why would the attribute being public interfere with changing it?
Bombepengu1nx, the “contract” of a class is the public API it offers, i.e. all the methods you can use to interact with it.
BombeIf you make fields public, they become part of that contract.
BombeWhich can be fine, mind you, but it does make some things harder: testing involving mocks and public final fields is a mess, and if you want to change how you store certain properties, you now can’t, because every client of your class expects the field to be of type X.
BombeIf you supply an accessor to get to the value of the field, you’re free to change the representation within your class, how it’s stored, how it’s processed, and the accessor can take care of turning it into the X the clients expect.
BombeThat’s also called “encapsulation,” and it’s one of the basic principles of OOP.
nimajean easy example would be complex numbers, you can represent these in polar coordinates or in cartesian coordinates, if you start with one representation and later notice that the other representation would be better for your use case then you can just change the representation if the fields are not part of the public api and change the rest of the program later if at all
dreamrealA simple example: setPronunciation() and getPronunciation(). You might mutate the value on set such that it has an internal tokenization, while getting the value might SIMILARLY annotate the tokenization with whitespace, translation from unicode, whatever. The external value and the internal value representations don't have to be the same.
dmlloydanother thing that is rarely mentioned is that people almost never write Java classes that are just getters and setters of simple data fields in practice; that's like something you only do commonly in introductory examples most of the time
ParaWalk before you run.
kcomhnal1dmlloyd: pretty much. I just use @Data
kcomhnal1eewww... I'm a clone.
kcomhnallnow its okay
dmlloydI think a far better example is a class with final fields and just getters tbh
dmlloydrecords cover that case about 80% of the time
kcomhnallwhat do you guys use to model your schema / hierarchy ? Figma?