Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Last active December 28, 2015 04:59
Show Gist options
  • Save nicklockwood/7446228 to your computer and use it in GitHub Desktop.
Save nicklockwood/7446228 to your computer and use it in GitHub Desktop.
Why having a single success/error callback block is better than having separate ones

Suppose you have a network method that only uses a single block callback

typedef void (^Handler)(BOOL success, id response, NSError *error);

- (void)makeRequestWithHandler:(Handler)handler;

But you have to make this request dozens of times, and you want to reuse the same failure handler in most cases? Easy, just have a factory function that returns a block:

typedef void (^SuccessHandler)(id response);
typedef void (^ErrorHandler)(NSError *error);

Handler makeHandler(SuccessHandler successBlock, ErrorHandler errorBlock)
{
    return ^(BOOL success, id response, NSError *error)
    {
        if (success)
        {
            if (successBlock) successBlock(response);
        }
        else
        {
            if (errorBlock) errorBlock(error);
        }
    }
}

Now you can elegantly call your singler-handler function with seperate success/failure handlers whenever you feel like it:

[[MyNetworkClass sharedInstance] makeRequestWithHandler:makeHandler(^(id response) {

    //success code
    
}, ^(NSError *error) {

   //error code

})];

This also means that if you have a generic error handler, you can just change the error condition in your makeHandler function to:

if (errorBlock) errorBlock(error); else //generic error handling behaviour

And then to use this fallback, just call your network method as follows:

[[MyNetworkClass sharedInstance] makeRequestWithHandler:makeHandler(^(id response) {

    //success code
    
}, NULL)];

And this makeHandler method could even be built into the network library, with various standard implementations for your convenience.

So having a single callback gives you huge flexibility. Having seprate success/failure handlers built into the network method interface would force you to always specify two parameters; there's no easy way to make an equivalent factory function that takes a single handler block and splits it into two.

@RuiAAPeres
Copy link

@bvanderveen The problem with ReactiveCocoa, is that you perfectly ok to use on your own stuff. In many places it's just plain impossible. The time it would take to new comers to understand: 1) Your app architecture 2) Work effectively with ReactiveCocoa 3) The company actually accepts the use of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment