程序的容错性很重要.
容错性越好,兼容性就越好.比如浏览器解析css时就有很灵活的容错性.当遇到错误的css样式时就直接忽略,而不会报错.忽略错误的样式,就是容错.有什么好处呢?体现在浏览器的兼容性上.比如border-radius是HTML5的属性,IE9支持,但是IE8支持.可是我们再IE8中运行时依然正常,而不会因为报错导致不解析网页样式.
Java中也有容错性.比如我之前写了一个方法
@Deprecated
public static String getFullContent(File file) {
BufferedReader reader = null;
if (!file.exists()) {
System.out.println("getFullContent: file(" + file.getAbsolutePath()
+ ") does not exist.");
return null;
}
try {
reader = getBufferReaderFromFile(file);
return getFullContent(reader);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
该方法只有一个参数,但是后来我发现应该增加一个参数编码,于是修改上述方法为:
public static String getFullContent(File file, String charset) {
BufferedReader reader = null;
if (!file.exists()) {
System.out.println("getFullContent: file(" + file.getAbsolutePath()
+ ") does not exist.");
return null;
}
if (charset == null) {
charset = SystemHWUtil.CHARSET_ISO88591;
}
try {
reader = getBufferReaderFromFile(file, charset);
return getFullContent(reader);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
修改完了就OK 了吗?
因为这是一个通用的工具类,所以只要用到这个方法的地方都报错了.为什么?因为方法签名改变了!!!
虽然我方法的功能增强了,可是我破坏了兼容性.
后来我增加一个方法:
public static String getFullContent(File file) {
return getFullContent(file, null);
}
就好了.
所以我就给自己定了一个规矩:以后增加一个方法的参数时,一定要保留原来的签名.
比如之前写了方法A(x,y)
后来扩充了功能,变为:A(x,y,z),那么我同时肯定会增加一个方法
A(x,y)
{
A(x,y,null)
}