4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Defensive Copy

Last updated at Posted at 2016-02-27

##Not-ImmutableなDateManagerクラス
todayへの参照がDateManagerインスタンスの生成時に渡されてしまい、
外部から値が変更できてしまう。

public class DateManager {

	private Date day;
	
	public DateManager(Date day){
		this.day = day;      // ・・・Bad 
	}
	
	public Date getMyDay(){
		return day;          // ・・・Bad
	}
	
	public String toString(){
		return day.toLocaleString();
	}
	
	public static void main(String[] args){
		Date today = new Date();
		DateManager dm = new DateManager(today);
		
		System.out.println(dm); // 2016/02/27 13:18:17
		day.setHours(11);	
		System.out.println(dm); // 2016/02/27 11:18:17
	}
}

##ImmutableなDateManagerクラス
オブジェクトを共有しないように新しいDate型を生成する。
Cloneでも良さそうだがクラスに参照型オブジェクトや配列のフィールドがあると、
オブジェクトを共有する形でコピーを作成するため問題が解決しない。

public class DateManager {

	private Date day;
	
	public DateManager(Date day){
		this.day = new Date(day.getTime()); 
	}
	
	public Date getMyDay(){
		return new Date(day.getTime());      
	}
	
	public String toString(){
		return day.toLocaleString();
	}
	
	public static void main(String[] args){
		Date today = new Date();
		DateManager dm = new DateManager(today);
		
		System.out.println(dm); // 2016/02/27 13:18:17
		day.setHours(11);	
		System.out.println(dm); // 2016/02/27 13:18:17
	}
}
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?