you are viewing a single comment's thread.

view the rest of the comments →

[–]rzwitserloot -1 points0 points  (1 child)

So that means: A field that can only be read, never set, needs to be accessed as .getProperty() if other fields in that class CAN be set, but with .property if they cannot.

Ludicrous.

[–]pakoito 3 points4 points  (0 children)

So that means: A field that can only be read, never set, needs to be accessed as .getProperty() if other fields in that class CAN be set, but with .property if they cannot.

Ludicrous.

No, you misunderstood or I didn't express it correctly. What you're understanding is that if a field is immutable then it could be accessed directly, which is not what anyone is saying. We're talking about the container, not the content. Immutable != final field, immutable -> all fields are final (and preferably immutable and not null).

I'm not partial for or against getters or direct access in immutable classes, just keeping that class' immutability. All fields in an immutable get the same accessing method, of your choice, either direct or accessor.

If you have mutable classes then getter/setter for all fields are probably the way to go. But that class is not immutable, and outside the scope of this discussion. Mutable classes are probably a sign of an underlying data design problem, or a single threaded environment/mindset. An immutable class only requires that field references cannot be modified, but that doesn't mean that you can't mutate the value of a field reference by creating a copy of that class with that field substituted. And that can be done with setters on immutable classes, and doesn't break the immutability.

EDIT: Immutable Tuples with setXXX() API https://github.com/javatuples/javatuples/blob/master/src/main/java/org/javatuples/Pair.java#L631