3 ms·
Well, actually, since the getters/setters advertise the type of the internal data structure, it is public. True, you could change the return type of them (which
by halosghost 11y ago
Well, actually, since the getters/setters advertise the type of the internal data structure, it is public. True, you could change the return type of them (which would require you to do just as much refactoring as if you changed a public internal data structure) or change the internal data structure and cast to the return type but many times that will make the getter/setter meaningless.
This is all not to mention that since the setter is public, you don't have any protection of your internal data structure anyway since anyone can modify it.
It's true that getters/setters offer thread-safety; I'm happy to concede that.
However, the performance impact is not FUD (or at least, I did not mean it as such); ask any systems programmer and they will happily tell you that one of the most common optimizations you can make is removing function calls where they are unneeded. Another comment mentioned that the JVM can JIT this problem away through inlining; I honestly do not know if that it is true—if it is, then great; that would be a significant benefit over this same kind of formulation in, say, Cxx.
Finally though, I don't really understand why Java programmers cling to backwards compatibility so when their own language shows you what happens when you commit to never removing anything to avoid breakage (i.e., you build in a huge amount of cruft).
Keep in mind, none of my posts are meant to be flamey here; I was just giving my opinion of one of the patterns displayed in the FAQ that I find distressing.
- lemming 11y agosince the getters/setters advertise the type of the internal data structure No, they don't - that's the whole point. You can change the type of your internal data structure however you want, but as long as the getters and setters accept and return the same type, your contract remains the same with your clients. since the setter is public, you don't have any protection of your internal data structure anyway since anyone can modify it Of course you do. You can check invariants in your setter before applying any changes, and throw an exception if the passed value violates them. You can take a lock in your setter, to ensure that the passed information is applied in a thread-safe way. Again, this is the whole point of encapsulation. Another comment mentioned that the JVM can JIT this problem away through inlining; I honestly do not know if that it is true—if it is, then great The JVM can do this, and much much more, at runtime. Basing your optimisation advice on what a systems programmer might have told you 20 years ago is a really bad idea. All good JITs and compilers have inlined small functions for a very long time now. The JVM is particularly impressive in that it can do that for virtual calls too.