Week 92 — What is a "defensive copy" and what is its purpose?
Question of the Week #92
What is a "defensive copy" and what is its purpose?
1 Reply
When storing an object, change from external sources is often unwanted and cause issues. For example, take the following code:
If some other code modifies the
List
passed to the constructor of SomeClass
between the isEmpty
and removeFirst
method invocations, it would be possible that removeFirst
throws a NoSuchElementException
even though isEmpty
returned false
before.
In order to prevent issues like that, it is possible to create a copy of the List
in the constructor and use that. The idea of making a copy of an object in order to protect that object from unwanted modification is called defensive copying.
Because external code doesn't have access to the internal List
used by SomeClass
, that code cannot accidentially cause issues in these methods.📖 Sample answer from dan1st