ByteCode.News
Submit RSS Atom Sign in

Back to the channels

#java

  1. pengu1nx Why are attributes often private, but then have a getter and setter?
  2. Swayze a design pattern that emerged out of the need to often validate values before assigning them
  3. Swayze also you can change complex internal logic without changing your classes contract
  4. NeXeN never reach into private members, we all learned that in kindergarten
  5. Swayze hes asking WHY they're private to begin with
  6. Swayze (you CANT reach into private members)
  7. NeXeN but my joke is funnier
  8. pengu1nx I 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?
  9. Bombe pengu1nx, the “contract” of a class is the public API it offers, i.e. all the methods you can use to interact with it.
  10. Bombe If you make fields public, they become part of that contract.
  11. Bombe Which 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.
  12. Bombe If 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.
  13. Bombe That’s also called “encapsulation,” and it’s one of the basic principles of OOP.
  14. nimaje an 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
  15. dreamreal A 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.
  16. dmlloyd another 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
  17. Para Walk before you run.
  18. kcomhnal1 dmlloyd: pretty much. I just use @Data
  19. kcomhnal1 eewww... I'm a clone.
  20. kcomhnall now its okay
  21. dmlloyd I think a far better example is a class with final fields and just getters tbh
  22. dmlloyd records cover that case about 80% of the time
  23. kcomhnall what do you guys use to model your schema / hierarchy ? Figma?