Cocoa Asynchronous API Design
Cocoa Asynchronous API Design
- Subject: Cocoa Asynchronous API Design
- From: Tito Ciuro <email@hidden>
- Date: Tue, 24 May 2011 08:25:01 -0700
Hello,
I have a question about Cocoa API design. I think I can give a concrete example to best explain what the goal is. Assume I have an Inventory service and I need to write a client API that deals with it. Goals:
- The API should allow me to add, update, delete and search items
- These operations should be asynchronous
Path #1:
Public method: - (void)addInventoryItem:(MyInventoryItem *)inventoryItem;
Implement a protocol for each of the actions (i.e. add, update, delete and search. See URLConnection, "Connection Completion" section) Example:
- Delegate method if successful: - (void)itemAdditionDidSucceed:(MyInventoryItem *)accountInfo;
- Delegate method if failure: - (void)itemAddition:(MyInventoryItem *)accountInfo didFailWithError:(NSError *)error;
Pros: the delegate method can receive specific data objects specific to the operation (i.e. MyInventoryItem for addInventoryItem vs NSArray for searchInventory)
Cons: the protocol could end up being verbose, with many delegates to be implemented (i.e. success/failure for add, update, delete and search... 8 methods in total)
Path #2:
Implement a protocol with two methods: success and failure (see URLConnection, "Connection Completion" section)
Implement an action class that encapsulates the action (i.e. add, update, delete and search) and the actual data needed for the operation
Public method: - (void)addInventoryItem:(MyInventoryAction *)inventoryAction;
Delegate method if successful: - (void)actionDidSucceed:(MyInventoryAction *) inventoryAction;
Delegate method if failure: - (void)action:(MyInventoryAction *) inventoryAction didFailWithError:(NSError *)error;
Pros: simplifies the number of delegate methods
Cons: when the delegate method gets called, we have to introspect to obtain the action and associated data. Also, the data could be a single inventory item (i.e. add, update, delete) or an array of them (i.e. search), so we would have to cast the return type (id since it's generic) to its proper class based on the type of action.
Which option do you feel is better? Would you consider a different solution? I really don't mind if the implementation is more complex if that makes the life of the developer easier. Perhaps Path #2 is better because it would simplify the Client code, but I would like to hear what other developers think.
Thanks in advance,
-- Tito
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden