...
Mutable classes that define a clone()
method must be declared final
.
Compliant Solution (unmodifiable Date wrapper)
If cloning or copying a mutable object is infeasible or expensive, one alternative is to create an unmodifiable view class. This class overrides mutable methods to throw an exception, protecting the mutable class.
Code Block | ||
---|---|---|
| ||
class UnmodifiableDateView extends Date {
private Date date;
public UnmodifiableDateView(Date date) {
this.date = date;
}
public void setTime(long date) {
throw new UnsupportedOperationException();
}
// Override all other mutator methods to throw UnsupportedOperationException
}
public final class MutableClass {
private Date date;
public MutableClass(Date d) {
this.date = d;
}
public void setDate(Date d) {
this.date = (Date) d.clone();
}
public UnmodifiableDateView getDate() {
return new UnmodifiableDateView(date);
}
}
|
Exceptions
OBJ08-EX1: Sensitive classes should not be cloneable, per guideline "OBJ03-J. Sensitive classes must not let themselves be copied."
...