Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why using 'assert' in a project? (and why using it so many times)

i was reading through the sample code ListAdder, and there are many asserts right after the variable, or used in almost every method, for example :

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

or :

- (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));

I was wondering, what's the point to do that?

Thanks

like image 292
Paul Avatar asked Oct 06 '11 17:10

Paul


2 Answers

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:

  • http://www.roard.com/contracts/
  • http://lists.apple.com/archives/objc-language/2006/Sep/msg00000.html
  • The D programming language has DbC, and here is Michel Fortins attempt at the same style of DbC, but for Objective C: http://michelf.com/weblog/2010/dobjc-preliminary-design/
like image 122
Prof. Falken Avatar answered Sep 28 '22 00:09

Prof. Falken


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.

like image 44
Catfish_Man Avatar answered Sep 28 '22 02:09

Catfish_Man