How to solve EI_EXPOSE_REP2 and why exactly its wrong

date, findbugs, java

Solution

I would recommend performing your `(Date) dataNascimento.clone()` call in the constructor (either directly, or via your setter).

Yes, FindBugs is warning you due to the fact that data is mutable. You may have the clone calls in your setters and getters, but you would still get the warning, since you could still might be able alter the the date inside the constructor.

Problem

I ran the FindBugs in my project, and I got the following warning: `new foo.pkg.Key(Client, Product, Date, String)` may expose internal representation by storing an externally mutable object into `Key.expireDate` MALICIOUS_CODE EI_EXPOSE_REP2 60 Medium `Key` is an Entity which have a `Date expireDate`, with its respective getter and setter, and it uses them in the constructor. Actually, I just return a `(Date) dataNascimento.clone()`, and use the same strategy in the setter. Questions (in backwards logical-order): - Is that the better way of doing this? - What was wrong with the previous code? - Why exactly is it wrong to do this? - Is it because Date is a mutable type?

Original source

Related problems