create changelog entry
[debian/openrocket] / core / src / net / sf / openrocket / util / Mutable.java
1 package net.sf.openrocket.util;
2
3 import net.sf.openrocket.logging.TraceException;
4
5 /**
6  * A utility class helping an object to be made immutable after a certain point of time.
7  * An object should contain an instance of Mutable and an immute() method which calls
8  * {@link #immute()}.  Additionally, every method that changes the state of the object
9  * should call {@link #check()} before modification.
10  * <p>
11  * This class also provides a stack trace of the position where the object was made
12  * immutable to help in debugging modifications of immuted objects.
13  * 
14  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
15  */
16 public class Mutable implements Cloneable {
17         
18         private TraceException immuteTrace = null;
19         
20         /**
21          * Mark the object immutable.  Once the object has been called the object
22          * cannot be made mutable again.  Repeated calls to this method have no effect.
23          */
24         public void immute() {
25                 if (immuteTrace == null) {
26                         immuteTrace = new TraceException(1, 2);
27                 }
28         }
29         
30         /**
31          * Check that the object is still mutable, and throw an exception if it is not.
32          * <p>
33          * The thrown exception will contain a trace of the position where the object was made
34          * immutable to help in debugging.
35          * 
36          * @throws      IllegalStateException   if {@link #immute()} has been called for this object.
37          */
38         public void check() {
39                 if (immuteTrace != null) {
40                         throw new IllegalStateException("Object has been made immutable at "
41                                         + immuteTrace.getMessage(), immuteTrace);
42                 }
43         }
44         
45         /**
46          * Check whether this object is still mutable.
47          * 
48          * @return      whether this object is still mutable.
49          */
50         public boolean isMutable() {
51                 return immuteTrace == null;
52         }
53         
54         
55         /**
56          * Return a new Mutable instance with the same state as the current object.
57          */
58         @Override
59         public Mutable clone() {
60                 try {
61                         return (Mutable) super.clone();
62                 } catch (CloneNotSupportedException e) {
63                         throw new BugException("CloneNotSupportedException", e);
64                 }
65         }
66 }