防御性编程

1,防御性编程。必要时应当考虑采取保护性拷贝的手段来保护内部的私有数据,先来看下面这个例子:

pubic final class Period
{
private final Date start;
private final Date end;

public Period(Date start, Date end)
{
if (start.compareTo(end) > 0)
throw new IllegalArgumentException(start + "after " + end);
this.start = start;
this.end = end;
}

public Date getStart()
{
return start;
}
public Date getEnd()
{
return end;
}
}

这个类存在两个不安全的地方,首先来看第一个攻击代码

Date start = new Date();
Date end = new Date();
Period p = new Period(start, end);
end.setYear(78);//改变p的内部数据!

这是因为外部和内部引用了同样的数据,为了解决这个问题,应当修改Period的构造函数:

public Period(Date start, Date end)
{
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (start.compareTo(end) > 0)
throw new IllegalArgumentException(start + "after " + end);
}

这样内部的私有数据就与外部对象指向不同,则不会被外部改变

再来看第二个攻击代码:

Date start = new Date();
Date end = new Date();
Period p = new Period(start, end);
p.getEnd().setYear(78);//改变p的内部数据!

这很显然是由于公有方法暴露了内部私有数据,我们可以只返回内部私有数据的只读版本(即其一份拷贝)

public Date getStart()
{
return (Date)start.clone();
}
public Date getEnd()
{
return (Date)end.clone();
}

2,读到上面这个例子,我想起来了下面这样的代码片段

public class Suit
{
private final String name;
private static int nextOrdinal = 0;
private final int ordinal = nextOrdinal++;

private Suit(String name)
{
this.name = name;
}
public String toString()
{
return name;
}
public int compareTo(Object o)
{
return o
}
public static final Suit CLUBS = new Suit("Clubs");
public static final Suit DIAMONDS = new Suit("diamonds");
public static final Suit HEARTS = new Suit("hearts");
public static final Suit SPADES = new Suit("spades");

private static final Suit[] PRIVATE_VALUES = {CLUBS,DIAMONDS,HEARTS,SPADES};
public static final List VALUES = Collections.unmodifiedList(Arrays.asList(PRIVATE_VALUES));


}



作者:洞庭散人

出处:http://phinecos.cnblogs.com/    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值