Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one vs. two completion blocks

I'm using a network kit that uses the twoBlock approach, but I prefer using the oneBlock in my own code. Which makes me confused if the twoBlock approach is better. Somehow I don't see it.

Is there any way that one approach is better than the other approach?


oneBlock approach

1 block that combines data and error:

-(void)oneBlock {
    [self startWithCompletionBlock:^(id obj, NSError* error) {
        if(error) {
            NSLog(@"error: %@", error);
        } else {
            NSLog(@"success: %@", obj);
        }
    }];
}

twoBlock approach

2 blocks that is dedicated to handling data and error:

-(void)twoBlocks {
    [self startWithCompletionBlock:^(id obj) {
        NSLog(@"success: %@", obj);
    } errorBlock:^(NSError* error) {
        NSLog(@"error: %@", error);
    }];
}
like image 952
neoneye Avatar asked Feb 19 '23 17:02

neoneye


1 Answers

I don't think you can say that either one is better. There is simply a different balance of pros and cons.

The main advantage of the two blocks approach is that you get a better separation of code for the "happy" path and code for error management. (This separation sounds similar to one of the advantages offered by the use of exceptions, but is a different beast; indeed, catch blocks allow to collect in one place, i.e., outside of your "functional" block, all the code to manage a bunch of possible error conditions that may arise within the "functional" block and whose management would be normally scattered all over it; in the 2-blocks example above, there is none of this, since the code to manage the error condition still appears intermixed with the rest of the code of your function).

On the other hand, it may well happen that in both cases, i.e., success and failures, you would like to take some common action. Think of, e.g., serializing a bunch of network operation: when one operation completes, you execute the next, both when the former operation was completed with success or failure. This is clearly a case where you will have some replication of code if using the 2-block approach.

Overall, I don't believe there is a great deal of a difference, since you can easily do what you need to do with both approaches, but in specific cases, one approach can fit your workflow better than the other.

Just my 2 cents.

like image 199
sergio Avatar answered Feb 28 '23 12:02

sergio