...
This example also violates OBJ37-J. Do not return references to private dataDefensively copy private mutable class members before returning their references.
Compliant Solution
This compliant solution highlights a custom container called ImmutableHolder
. When value
is assigned in ImmutableHolder
's constructor, it is a younger object that is referencing an older one (Hashtable<Integer, String> ht
). This is a much better position to be in as far as the garbage collector is concerned. Note that a shallow copy is used in this case to preserve references to the older value.
...