Sonar says that mutable members should not be stored or returned directly
Mutable objects are those whose state can be changed. For instance, an array is mutable, but a String is not. Mutable class members should never be returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state.
Instead, a copy of the mutable object should be made, and that copy should be stored or returned.
This rule checks that arrays, collections and Dates are not stored or returned directly.
I'm trying to store one date. To solve the sonar alert, I created two helper methods to return a copy of my original date.
Example A:
public static Date clone(Date originalDate) {
if(date != null) {
return new Date(originalDate.getTime());
}
return null;
}
Example B:
public static Date clone(Date originalDate) {
if (date != null) {
return (Date)originalDate.clone();
}
return null;
}
If I use the constructor way (example A), I loose the possible extra information that contains my original date.
Should I copy my originalDate with the constructor (example A) or with clone (example B)?