Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deal with asynchronous spaghetti code?

I am writing a simple application using the Facebook iPhone SDK. The Facebook code is mostly asynchronous, I start an operation and receive the response asynchronously in a delegate call:

- (void) doSomething {
    [FBSomething startOperationWithDelegate:self];
}

- (void) fbOperationFinished: (FBSomething*) operation {…}

Quite often there are more instances of a given operation (say FBRequest) that use the same callback. This means that I have to put a conditional clause into the callback handler to know which of these operations finished.

This leads to messy, a kind of “asynchronous spaghetti code” monster because the code is full of conditionals and it’s almost impossible to see the program flow logic. Is there a better way to write such code? (It’s a shame we don’t have blocks on iPhone.) I thought about introducing a simple state machine, but I’m not sure it will help.

like image 780
zoul Avatar asked Dec 09 '22 17:12

zoul


2 Answers

I'm not familiar with the Facebook SDK, but you could just create a subclass that implements the FBRequestDelegate protocol (if it's called like that) for every specific task you need Facebook for. This way, you have say 5 classes implementing - fbOperationFinished: rather than one class with 5 different execution paths separated by ifs or switches.

like image 95
MrMage Avatar answered Dec 20 '22 22:12

MrMage


There is no need to subclass the Facebook API objects. I would highly recommend against that.

All the facebook objects have a userInfo field that you can use to store request specific information. So you can store something in there to identify the request or even a reference to an object to deal with the request.

That is much cleaner and more in the style of the Cocoa frameworks.

like image 42
Stefan Arentz Avatar answered Dec 20 '22 22:12

Stefan Arentz