This question is about good programming practices and avoiding potential holes.
I read Joshua Bloch’s Effective Java and here is what I wonder:
Why should I consider making defensive copies in getter methods in my immutable class with no mutators in it?
And second: why should I make my fields final in addition to private ? Is this only about performance (not security) ?
This question is about good programming practices and avoiding potential holes. I read Joshua
Share
I believe this is the case that justifies this statements:
getName()is fine as it returns immutable object as well. However thegetDateOfBirth()method can break immutability because the client code can modify returned object, hence modifying theImmutableobject as well:It is safe to return immutable objects and primitives (as they are returned by value). However you need to make defensive copies of mutable objects, like
Date:and wrap collections in immutable views (if they are mutable), e.g. see
Collections.unmodifiableList():