码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:objective   objective-c   防御式编程   

优点:

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

例代码:

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

- (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----防御式编程

标签:objective   objective-c   防御式编程   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!