One should not expose the reference to a non final field if one wants to construct an immutable class - but even for immutable objects like Strings ?
public final class Test { // Test class is meant to be immutable
private String s; // CAN'T MAKE THIS FINAL
void onCreate(String s) { // a callback called ONCE after construction
this.s = new String(s); // do I need to do this ? (protect me from me)
}
public String getS() {
return new String(s); //do I need to do this ?(protect me from the world)
}
}
It does not matter whether this class is immutable (for any definition of immutable). In particular, it does not matter if the reference s
is ever changed to point to a different string. The string object is immutable, so you don't need to copy it. Without defensive copying, callers of getS
will get references to the same string object used by Test
's methods and by other callers of getS
. That does not matter because nothing1 they do to this string will affect other referents. It'd be a waste of time and memory.
1 I'm ignoring reflection. Code that maliciously uses reflection like this can break almost anything, and is not written by accident or hard to spot. It is not even remotely practical to worry about this case.