Should my Block-based API have just completion or both success and failure handlers?

后端 未结 3 1871
闹比i
闹比i 2021-02-02 17:22

When designing a block-based API in ObjC, which approach is better, one completion block or two, one each for success and failure?

Let\'s say we have a method retrieving

3条回答
  •  日久生厌
    2021-02-02 17:54

    I generally use the second implementation. A few reasons for it:

    1. It works better for re-use blocks. I often have the same implementation for failures so I can just create a method that returns the failure block and change the success block as necessary. You could do this with the first implementation but you would need nested blocks then.

    2. I like to avoid unnecessary checks when possible ("if error then do something with my error otherwise do something with my object"). Since I will either get an object or an error (never both), I find it inconvenient to pass in both parameters when only one will ever be valid.

    3. I use Restkit and I just need to pass the blocks into my API calls and it will automatically call the success or failure block when the call comes in. If I do the second implementation I need to handle the method callbacks (failure or success method/block) and execute the block manually. I am not sure about AFNetworking though.

    I personally think both are fine but in this situation I would argue for the second.

提交回复
热议问题