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
0x150
0x1504mo ago
When storing an object, change from external sources is often unwanted and cause issues. For example, take the following code:
public class SomeClass {
private List<String> someList;
public SomeClass(List<String> someList){
this.someList = someList;
}
public String takeFirstElement() {
if(!someList.isEmpty()) {
return someList.removeFirst();
}
return null;
}
}
public class SomeClass {
private List<String> someList;
public SomeClass(List<String> someList){
this.someList = someList;
}
public String takeFirstElement() {
if(!someList.isEmpty()) {
return someList.removeFirst();
}
return null;
}
}
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.
public class SomeClass {
private List<String> someList;
public SomeClass(List<String> someList){
this.someList = new ArrayList<>(someList);//make a defensive copy of someList
}
public String takeFirstElement() {
if(!someList.isEmpty()) {
return someList.removeFirst();
}
return null;
}
}
public class SomeClass {
private List<String> someList;
public SomeClass(List<String> someList){
this.someList = new ArrayList<>(someList);//make a defensive copy of someList
}
public String takeFirstElement() {
if(!someList.isEmpty()) {
return someList.removeFirst();
}
return null;
}
}
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

Did you find this page helpful?