MALICIOUS_CODE EI_EXPOSE_REP Medium
Yeah, I wouldn't really call it a ‘security’ issue as such... I mean, what attacker exactly is going to be writing malicious code against your objects? The real problem would be that you're quite likely yourself to trip up by accidentally calling getBirthDate
then modifying the result.
For this reason, it is common to have your getter clone mutable objects like Date
for returning, when you're using them as value types.
(You could also argue that Java's Date
shouldn't have been made mutable, but there's not much can be done about that now.)
Adding to the good answer of Matt Solnit, I've faced the same problem when setting a attribute, so I did the same:
public void setDataEmissaoNota (Date dataEmissaoNota)
{
this.dataEmissaoNota = new Date(dataEmissaoNota.getTime());
}
Work's fine!
I think the key here is the if:
If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different.
So in other words, if you wanted an immutable object (i.e. you didn't have a setBirthdate()
method), your code be incorrect, because someone could write:
Date date = user.getBirthDate();
date.setMonth(1); // mutated!
So you would probably want the following instead:
public Date getBirthDate()
{return new Date(birthDate.getTime());} // essentially a clone