Step 1: make sure no one from outside the class can change the state variables. This can be done easily by declaring them final. You can also declare them private and ensure that there are no mutator methods ("setters").
Step 2: prevent subclassing and overriding of methods to change behavior or add mutable behavior. This is easily done by declaring your class "final".
Step 3: prevent outside references to state variables of reference (object) type. Mutable objects passed into the constructor could still be referenced by code on the outside of our object. Upon receipt of objects from the outside, make a copy to store as the state value. Example:
public final class MyThingy {
private final Point fPoint;
public MyThingy(Point point){
fPoint = point.clone();//easy, since Point implements Clonable
}
Now, whoever passed in point can change it's state, say by calling point.setLocation(x, y), and it doesn't efect my instance of MyThing, because my instance variable fPoint refers to a different Point object!
Step 4: prevent outside references to state objects accessed through accessor methods ("getters"). This is done by making what are called "defensive copies" and returning those vice your actual instance variables.
Example:
public Point getPoint(){
return fPoint.clone();
}
Now, someone who calls getPoint() will not be able to change the Point value for my instance of MyThingy.
2007-03-08 05:00:28
·
answer #1
·
answered by vincentgl 5
·
0⤊
0⤋