容错性

程序的容错性很重要.

容错性越好,兼容性就越好.比如浏览器解析css时就有很灵活的容错性.当遇到错误的css样式时就直接忽略,而不会报错.忽略错误的样式,就是容错.有什么好处呢?体现在浏览器的兼容性上.比如border-radius是HTML5的属性,IE9支持,但是IE8支持.可是我们再IE8中运行时依然正常,而不会因为报错导致不解析网页样式.

 

Java中也有容错性.比如我之前写了一个方法

Java代码   收藏代码
  1. @Deprecated  
  2.     public static String getFullContent(File file) {  
  3.         BufferedReader reader = null;  
  4.         if (!file.exists()) {  
  5.             System.out.println("getFullContent: file(" + file.getAbsolutePath()  
  6.                     + ") does not exist.");  
  7.             return null;  
  8.         }  
  9.           
  10.         try {  
  11.             reader = getBufferReaderFromFile(file);  
  12.             return getFullContent(reader);  
  13.         } catch (FileNotFoundException e1) {  
  14.             e1.printStackTrace();  
  15.         } finally {  
  16.             if (null != reader) {  
  17.                 try {  
  18.                     reader.close();  
  19.                 } catch (IOException e) {  
  20.                     e.printStackTrace();  
  21.                 }  
  22.             }  
  23.         }  
  24.         return null;  
  25.     }  

 该方法只有一个参数,但是后来我发现应该增加一个参数编码,于是修改上述方法为:

Java代码   收藏代码
  1. public static String getFullContent(File file, String charset) {  
  2.         BufferedReader reader = null;  
  3.         if (!file.exists()) {  
  4.             System.out.println("getFullContent: file(" + file.getAbsolutePath()  
  5.                     + ") does not exist.");  
  6.             return null;  
  7.         }  
  8.         if (charset == null) {  
  9.             charset = SystemHWUtil.CHARSET_ISO88591;  
  10.         }  
  11.         try {  
  12.             reader = getBufferReaderFromFile(file, charset);  
  13.             return getFullContent(reader);  
  14.         } catch (FileNotFoundException e1) {  
  15.             e1.printStackTrace();  
  16.         } finally {  
  17.             if (null != reader) {  
  18.                 try {  
  19.                     reader.close();  
  20.                 } catch (IOException e) {  
  21.                     e.printStackTrace();  
  22.                 }  
  23.             }  
  24.         }  
  25.         return null;  
  26.     }  

 修改完了就OK 了吗?

 

因为这是一个通用的工具类,所以只要用到这个方法的地方都报错了.为什么?因为方法签名改变了!!!

虽然我方法的功能增强了,可是我破坏了兼容性.

后来我增加一个方法:

Java代码   收藏代码
  1. public static String getFullContent(File file) {  
  2.         return getFullContent(file, null);  
  3.     }  

 就好了.

 

所以我就给自己定了一个规矩:以后增加一个方法的参数时,一定要保留原来的签名.

比如之前写了方法A(x,y)

后来扩充了功能,变为:A(x,y,z),那么我同时肯定会增加一个方法

A(x,y)

{

   A(x,y,null)

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值