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

3

6

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

Presidium answered 6/10, 2011 at 17:0 Comment(0)
D
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:

Dachshund answered 6/10, 2011 at 17:3 Comment(0)
B
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.

Benefaction answered 6/10, 2011 at 17:2 Comment(0)
G
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.

Gatlin answered 6/10, 2011 at 17:2 Comment(1)
I don't know about Objective C but in other languages they can be disabled at compiled time so they don't slow down live systems, but you can use them for bug detection during testing and staging.Beardsley

© 2022 - 2024 — McMap. All rights reserved.