Re:Getter-Setter Pattern Considered Harmful
by Groxx on Sunday February 16, 2025 @12:04PM
(#43069537)
Unless it's synchronized. Then you could deadlock.
Re:Getter-Setter Pattern Considered Harmful
by mrkeen on Sunday February 16, 2025 @12:27PM
(#43069785)
This got me curious, so I tried it out.
I was unable to put a synchronized onto the field directly:
error: modifier synchronized not allowed here
public synchronized final Object field;
But when I locked it in code: synchronized (field) {
while(true) {
..
I was still able to access the synchronized field directly without triggering a deadlock - whereas a getter() could be synchronized and trigger a deadlock.In any case, the article already made a strong points for immutability so you don't need to mess around with deadlocking crap.
Re:Getter-Setter Pattern Considered Harmful
by jayd16 on Sunday February 16, 2025 @12:38PM
(#43069896)
They're saying multiple things can synchronize on the same public field. Same reason you don't want to use this.
Although I suppose they could mean the concept and not the keyword. A field might not be thread safe and there's no way for an object to guarantee thread safe access of to a field.
Re:Getter-Setter Pattern Considered Harmful
by mrkeen on Sunday February 16, 2025 @01:33PM
(#43070341)
Deadlocking was raised as the objection to using public instead of getter. But in regard to deadlocking, using public is strictly better than a getter.
You have to take a lock in order to deadlock in the public version. In the getter version, you can take a lock without realising it and then deadlock.
Re:Getter-Setter Pattern Considered Harmful
by Groxx on Sunday February 16, 2025 @05:28PM
(#43072385)
nope, sorry, that's my mistake. I'm misremembering java, it has been too long :) thanks for the correction!
Re:Getter-Setter Pattern Considered Harmful
by Pxtl on Monday February 17, 2025 @11:26AM
(#43080586)
To me that's just a matter of having standards that have clear requirements of what's okay to put in a getter - imho, refreshing invalidated caches (as long as they're lightweight and not like network communication) is perfectly appropriate. Anything with a side-effect that can be observed from outside of the object (creating the case where you get code just hitting setters and getters to cause side effects) is right out.
I mean, Lazy<T> is a great example of use of getters.
Accessing a field will not invoke other code.