concept mutable object in category security

appears as: mutable objects, mutable object
Secure by Design

This is an excerpt from Manning's book Secure by Design.

In this section, we want to share some common pitfalls of designs that don’t protect the integrity of entities, as well as ways of designing so that integrity is protected. We’ll look at some different cases: fields with getter and setter methods, mutable objects, and collections.

If for some reason you find yourself in a situation writing code where your only option is to work with a mutable object, there’s a trick. When your methods return a reference to an encapsulated object, first clone the object. In this way, you avoid having your mutable object changed by someone else. If they use the reference you give them to mutate the object, they’ll only change their copy, not your original. In the following listing, you see this trick applied to java.util.Date.

Listing 6.11 Person class that returns a clone of birthdate
class Person {

    private Date birthdate;

    Date birthdate() {
        return birthdate.clone();    #1  
    }
}

#1   Ensures that a copy is returned

Most often, it’s not too hard to avoid sharing mutable objects because many modern libraries have good immutable classes. But there’s one case that often surfaces as a problem—collections.