Defensive Copying 19 comments, 0 freshness points, 270 goodness points Submission of type Article by YoGee Jun 6, 2007 5:35:33 AM | Tags: Copying Defensive Immutable Mutable good safety thread | ||
An introduction to defensive copying. | ||
ContentProgramming defensively is an essential skill to learn if you want to produce a robust API. By implementing defensive copying you can avoid unwanted and unexpected behaviour that can compromise security and confuse your API clients. The key to understanding defensive copying is understanding the difference between a mutable and an immutable class. An immutable class is a class whose instances cannot be modified, for example the java.lang.String class. A mutable class is a class whose instances can be modified, for example the java.util.Date class. Whilst immutable objects are inherently thread safe, mutable objects are not, and this is when we need to consider making defensive copies. Take the following example:
This class is immutable, right? Wrong. Whilst it appears we cannot change the internal state of a Person Object after it has been instantiated this is actually not the case since dateOfBirth is a mutable parameter.
Result:
We have changed John Smith's DOB. To avoid this we can defensively copy dateOfBirth: (notice we do this when we set dateOfBirth and when we expose it)
Now it is not possible to modify the internal state of a Person Object after it has been instantiated and it is truly immutable (assuming we have an appropriate SecurityManager in place). Defensive copying isn't just for immutable classes, whenever you are dealing with a client provided Object consider if that Object is mutable and what the side effects could be if the client modifies that Object. |