Saturday, April 28, 2012

Defensive Copies



You must protected your classes from calling code. Assume that calling code will do its best to change your data in a way you didn't expect it. While this is especially true in case of immutable data it is also true for non-immutable data which you still not expect that this data is changed outside your class.
To protect your class against that you should copy data you receive and only return copies of data to calling code.
The following example creates a copy of a list (ArrayList) and returns only the copy of the list. This way the client of this class cannot remove elements from the list.
package com.po2cls.actions.performance.defensivecopy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyDataStructure {
 List<String> list = new ArrayList<String>();

 public void add(String s) {
  list.add(s);
 }
// Makes a defensive copy of the List and return it
//This way cannot modify the list itself
public List<String> getList() { return Collections.unmodifiableList(list); } }

No comments:

Post a Comment