...
The problem is alleviated by creating a copy of the mutable input and using it to perform operations so that the original object is left unscathed. This can be realized by implementing the java.lang.Cloneable interface and declaring a public clone method or by using a copy constructor. Performing a manual copy of object state within the caller becomes necessary if the mutable class is declared as final (that is, it cannot provide an accessible copy method). xyzxyz. Note that the input validation must follow after the creation of the copy.
Code Block | ||
---|---|---|
| ||
public final class MutableDemo { // java.net.HttpCookie is mutable public void copyMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } // create copy cookie = cookie.clone(); //check if cookie has expired if(cookie.hasExpired()) { //cookie is no longer valid, handle condition } doLogic(cookie); } } |
...