Search code examples
javafindbugseffective-java

EI_EXPOSE_REP2 setter method


Findbugs complains about date objects and suggests creation of defensive copies. I used copies in the constructor and getter method, but it is really necessary to create a defensive copy in setter method? Here is an example:

    public Info(Date created) {
        this.creationDate = new Date(created.getTime());
    }

    public Date getCreated() {
        return new Date(creationDate.getTime());
    }

    public void setCreated(Date created) {
        this.creationDate = created;
    }

Is there a way to get the original object and make changes?


Solution

  • If your class is a public API the setter needs a defensive copy, because an attacker could maliciously modify the Date passed to the setter after passing it, changing the internal state of your class in an unintended manner. It could bypass checks in the setter, because they work only when the method is called, and not after.

    The attacker doesn't need to "get" the original Date object: he can simply hold the passed reference and modify it after calling the setter.