4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
Hi,
I've questions that are based on the quote above. I'd break the quote to make asking individual questions simpler. My understand is that the entire quote below is a part of the solution on how to make a class immutable while it has some association with (external) mutable objects.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
don't allow those objects to be changed?
What if we only have access to those external mutable objects and we lack power to make those objects immutable? Is the following one of the solutions to that situation?
Don't provide methods that modify the mutable objects.
As far as this is concerned, we just need to make OUR class (*) not provide a method that delegates the responsibility of changing the value(s) of a mutable object via the setter method of the class, from which the mutable object is instantiated.
Why did I say that?
We are simply using a mutable object and therefore we can't possibly get rid of the potential setter method that may exist in the class, from which the mutable object is instantiated.
(*) OUR class = the class we are tasked to make immutable
Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
With the quote immediately above, I sort of get what you are trying to do but then I suppose, I'm not fully getting what you are suggesting. I hope you could help me understand this. For the ideas you suggested in the quote immediately above, I've written the working code (The code in the following post due to 3000-char limit here) to implement the idea you suggested.
I understand this is a lot to discuss but please help me understand the concepts. Many thanks.
Schmichael