Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Multiple Block Parameters to Method

In the Apple Docs, it says:

It’s best practice to use only one block argument to a method.

Is it ok to pass multiple block arguments; or should this be avoided?

Specifically here are a few options I'm working with (I'm hoping to use the first one):

-(void) doSomethingWithSuccessBlock:(void(^)(void))successBlock withFailureBlock:(void (^)(NSError *)) failureBlock

OR

-(BOOL) didDoSomethingWithFailureBlock:(void (^)(NSError *)) failureBlock

OR

-(void) doSomethingWithCallbackBlock:(void (^)(BOOL, NSError *)) callbackBlock
like image 221
BoombaleOsby Avatar asked Oct 19 '25 14:10

BoombaleOsby


1 Answers

Using more than one block as a parameter will warp your mind, curve your spine, and make the enemy win the war. (to paraphrase George Carlin)

Kidding aside, it's a good goal to only have 1 block parameter, but as others have pointed out, Apple has a number of classes who's methods take multiple blocks. Before designing an API that uses multiple block parameters, spend some time thinking about alternatives, and pondering what it does to readability and maintainability of your code. Is there a simpler way to accomplish the same goal? If multiple blocks is the cleanest way to accomplish your goal, then use it.

I think your example of a method that takes both a success block and a failure block is pretty reasonable. You could refactor it into a single block that takes a BOOL parameter "success" and interrogate that parameter in the block to decide what to do. (the CAAnimation delegate method animationDidStop:finished: uses this approach. Actually, so does the completion block in UIView animation, come to think of it.)

You'll have to decide if that makes the method and the blocks you pass to it simpler and cleaner or more complex.

like image 134
Duncan C Avatar answered Oct 21 '25 04:10

Duncan C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!