首页 > 其他 > 详细

Objective-C----防御式编程

时间:2015-06-19 11:50:39      阅读:240      评论:0      收藏:0      [点我收藏+]

优点:

防御式编程能够在开发早期发现错误。

例代码:

下面是相关存取方法的实现代码。

- (void)setTire:(Tire *)tire atIndex:(int)index {
   if (index < 0 || index > 3) {
      NSLog (@"bad index (%d) in setTire:atIndex:", index);
      exit (1);
   }
   tires[index] = tire;
}
- (Tire *)tireAtIndex:(int)index {
   if (index < 0 || index > 3) {
      NSLog (@"bad index (%d) in tireAtIndex", inddex);
      exit(1);
   }
   return (tires[index]);
}

tire 存取方法中使用了通用代码来检查 tires 实例变量的数组索引,以保证它是有效数值。如果数组索引超出了 0 到 3 的范围,那么程序就会输出错误信息并退出。该代码就是所谓的防御式编程,这是一种很好的编程思想。防御式编程能够在开发早期发现错误,比如 tires 数组的索引错误。

Objective-C----防御式编程

原文:http://blog.csdn.net/zhengang007/article/details/46559547

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!