6

我正在阅读示例代码 ListAdder,在变量之后有很多断言,或者几乎在每种方法中都使用了,例如:

self.formatter = [[[NSNumberFormatter alloc] init] autorelease]; assert(self.formatter != nil);

或者 :

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   #pragma unused(tv)
   #pragma unused(indexPath)
   UITableViewCell *    cell;

   assert(tv == self.tableView);
   assert(indexPath != NULL);
   assert(indexPath.section < kListAdderSectionIndexCount);
   assert(indexPath.row < ((indexPath.section == kListAdderSectionIndexNumbers) ? [self.numbers count] : 1));

我想知道,这样做有什么意义?

谢谢

4

3 回答 3

5

It is an implementation of Design by Contract, or DbC.

Objective C has no native support for the pre-conditions, post-conditions and invariants of DbC, but especially post- and preconditions can be implemented pretty well with macros.

Here are some other approaches to implement DbC in Objective C:

于 2011-10-06T17:03:34.990 回答
2

The point of assertions is to make sure that bugs show up immediately, and in easily diagnosable ways, instead of as subtle misbehavior later on. In this case, the developer of that code wants to guarantee that 4 conditions hold after their code runs.

于 2011-10-06T17:02:22.183 回答
2

The asserts check the programmer's assumptions about how the code will be invoked. If the assumptions are wrong, the assert will fail and throw an exception. This makes code fail as early as possible.

Whether to do this or not is a point of debate. It can be taken too far.

于 2011-10-06T17:02:56.520 回答