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

I read a sample ListAdder code, and there are many statements immediately after the variable or is used for 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 of doing this?

thanks

+6
source share
3 answers

This is an implementation of Design by Contract or DbC .

Target C does not have built-in support for preconditions, postconditions , and DbC invariants, but especially post and preconditions can be well implemented using macros.

Here are some other approaches to implementing DbC in Objective-C:

+5
source

The point of assertion is to make sure that errors appear immediately and in easily diagnosed ways, and not later as subtle wrong behavior. In this case, the developer of this code wants to guarantee that 4 conditions will be saved after they run the code.

+2
source

Statements verify the programmer's assumptions about how the code will be called. If the assumptions are false, the statement will fail and will throw an exception. This causes the code to crash as early as possible.

Whether this should be done or not is a moot point. This can be done too far.

+2
source

Source: https://habr.com/ru/post/898783/


All Articles