3 ms·
I agree and I hate getters, but I am one of those who still hasn't figure out how to do OOP correctly. Do you have an example or maybe some suggested reading? F
by stevebot 12y ago
I agree and I hate getters, but I am one of those who still hasn't figure out how to do OOP correctly. Do you have an example or maybe some suggested reading? For example, if I have a user object, with name, age, number, how would that work without get/set? I'd love to avoid it, I hate the bloat it creates, and also how frivolous it seems to test get/set.
- arjie 12y agoWell, the answer depends on the function, the purpose. I suppose he's saying that you should encapsulate with the object. For example, you have an OrderLine object, you don't `o.setStatus(CANCELLED)`, you `o.cancel()` etc.
- stevebot 12y agoThat examples makes sense, but what about Strings and other types? I'm not sure you can do the same thing for a User object with name, age etc. I'd love to not have getters/setters but I have yet to see a replacement for all get/set scenarios.
- arjie 12y agoThat's a Plain Old Data object and back in the day the Sun Java Coding Conventions recommended public instance variables for classes which "would have been a struct if Java supported it" or something like that. I suppose it's all about behaviour. If the class is literally just a struct - a box for data, there's no functionality to describe. Choosing public instance variables vs. getter/setter is just a matter of choice at that point. The latter let you check Preconditions, etc. but that means that you actually have some invariant you intend to preserve (date of birth of the user cannot be in the future, for instance, so your well-formed user has some characteristics). Any members that can take any value their type permits should, in my opinion, just be public. Logically if you perceive that you could have some invariant in the near future, you'd want to have getters/setters but there's no point overdoing it.
- jsmeaton 12y agoThe parent would have the `User` type as a value type, with read-only final fields.
- vetler 12y agoHere's a tip: instead of changing your objects, you can create a new object with the same values except the ones you want to change. Another option is to use builders (that are mutable), to build/copy your immutable business (?) objects.
- mercurial 12y agoThat's what we do at work. Then when work is done, I look at OCaml and repeat the mantra "I'm not going to think about how many lines it takes in Java to do a functional update 'let foo2 = { foo1 with foo_field = "bar" }'". It is possible to have immutable objects in Java and have the equivalent of functional updates, but it's a hell of a lot of pointless boilerplate. It still beats traditional Java beans, though.