Copy Mutable Parameters

ValueObjectsShouldBeImmutable. However, one sometimes has to use a mutable object as a ValueObject. If an object has to use a mutable object as a ValueObject, operations on the mutable value can change the object's internal state without its knowledge and can cause it's state to become inconsistent. For example, altering MartinFowler's example slightly:

	public class Task {
		public void setStartDate( Date d ) {
			_start_date = d;
		}
		...

private Date _start_date; }

... Date d = new Date( some-value ); Task task1; task1.setStartDate( d ); d.setDate( some-other-value );

Therefore: an object that holds mutable objects as state must ReturnNewObjectsFromAccessorMethods. Additionally, it must make private copies of mutable objects that are passed to it and that it needs to store internally. For example:

	public class Task {
		public void setStartDate( Date d ) {
			_start_date = (Date)d.clone();
		}
		...
	}

-- NatPryce


Except that clone is a bad idea here. If you can be certain that the input parameter is actually a bona fide java.util.Date, you are okay. But if other classes can get into the system, you have a security problem. Consider a BadDate class written as a Date subclass that has its own hook to the outside world. Call the setDtartDate method with it and the insecurity propagates. Better is:

	public class Task {
		public void setStartDate( Date d ) {
			_start_date = new Date(d.getTime());
		}
		...
	}

-- EricJablow
EditText of this page (last edited May 7, 2005)
FindPage by browsing or searching

This page mirrored in JavaIdioms as of April 29, 2006