Objective-c asynchronous communication: target/action or delegation pattern? - iphone

I'm dealing with some asynchronous communication situations (Event-driven XML parsing, NSURLConnection response processing, etc.). I'll try to briefly explain my problem:
In my current scenario, there is a service provider (that can talk to a xml parser or do some network communication) and a client that can ask the service provider to perform some of its tasks asynchronously. In this scenario, when the service provider finishes its processing, it must communicate back the results to the client.
I'm trying to find a kind of pattern or rule of thumb to implement this kind of things and I see 3 possible solutions:
1. Use the delegation pattern: the client is the service provider's delegate and it will receive the results upon task completion.
2. Use a target/action approach: The client asks the service provider to perform a task and pass a selector that will have to be invoked by the service provider once it has finished the task.
3. Use notifications.
(Update) After a while of trying solution #2 (target and actions), I came to the conclusion that, in my case, it is better to use the delegation approach (#1). Here are the pros and cons of each option, as I see them:
Delegation approach:
1 (+) The upside of option 1 is that we can check for compile-time errors because the client must implement the service provider's delegate protocol.
1 (-) This is also a downside because it causes the client to be tight-coupled with the service provider as it has to implement its delegate protocol.
1 (+) It allows the programmer to easily browse the code and find what method of the client, the service provider is invoking to pass its results.
1 (-) From the client point of view, it is not that easy to find what method will be invoked by the service provider once it has the results. It's still easy, just go to the delegate protocol methods and that's it, but the #2 approach is more direct.
1 (-) We have to write more code: Define the delegate protocol and implement it.
1 (-) Also, the delegation pattern should be used, indeed, to delegate behavior. This scenario wouldn't be an exact case of delegation, semantically speaking.
Action/Target Approach
2 (+) The upside of option 2 is that when the service provider method is being called, the #selector specifying the callback action must also be specified, so the programmer knows right there which method will be invoked back to process the results.
2 (-) In opposition to this, it's hard to find which method will be called back in the client while browsing the service provider code. The programmer must go to the service invocation and see which #selector is being passed along.
2 (+) It's a more dynamic solution, and causes less coupling between parts.
2 (-) Perhaps one of the most important things: It can cause run-time errors and side effects, as the client can pass a selector that does not exist to the service provider.
2 (-) Using the simple and standard approach (#performSelector:withArgument:withArgument:) the service provider can only pass up to 2 arguments.
Notifications:
I wouldn't choose notifications because I think they are supposed to be used when more than one object need to be updated. Also, in this situation, I'd like to tell directly the delegate/target object what to do after the results are built.
Conclusion: At this point, I would choose the delegation mechanism. This approach provides more safety and allows easily browsing the code to follow the consequences of sending the delegate the results of the service provider actions. The negative aspects about this solution are that: it is a more static solution, we need to write more code (Protocol related stuff) and, semantically speaking, we're not talking really about delegation because the service provider wouldn't be delegating anything.
Am I missing something? what do you recommend and why?
Thanks!

You did miss a third option – notifications.
You could have the client observe for a notification from the service provider indicating that it has new data available. When the client receives this notification it can consume the data from the service provider.
This allows for nice loose coupling; some of the decision is just down to whether you want a push/pull system though.

Very good question.
I dont think I am qualified, just yet (as I am a newbie), to comment on which design pattern is better than the other. But just wanted to mention that the downside you mentioned in point 2 (runtime exception) can be avoided by
if([delegate respondsToSelector:callback]){
//call to callback here
}
Hope that helps to weigh the options

Another downside for the Delegation approach:
A service provider can only have one delegate. If your service provider is a singleton, and you have multiple clients, this pattern does not work.
This caused me to go for the Action/Target approach. My service provider holds state and is shared among multiple clients.

Related

What design-pattern I should use in my notification system?

Which design-pattern I should use in this case:
I have a rest API notification system.
I can notify by Email
notify by push;
notify by WhatsApp.
And I want to implement more technologies, and I do not want to modify the core, I want to add only modules to the system. For example, adding Telegram Messages, Twitter messages, or another email provider.
Any recommendation?
According to your problem statement, two different types of design patterns will be involved:
1) Strategy Pattern: It will define the notification strategy based on the contexts like email, push, whatsapp, etc.
3) Observer Pattern: It will perform the publisher and subscribers operation will the behavior of loose coupling. It will automatically notify to subcriber.
You can also integrate RabbitMq somewhere for queuing and on time pushing messages.
The case you explained is like strategy design pattern . You can use strategy design pattern and have an interface and a class for your each system that implement your interface. These are links that can help you :
tutsplus design ptterns
designpatternsphp
For a notification system I would suggest you using the Observer pattern. The message you receive should be inside your Subject. Subject should allow any number of Observers to attach. When a message is received, the subject should notify all the observers. Then Observers can read the state/message from the subject and act upon it. I am not pretty much clear about your usecase. But this would do the job.
To me seems a PUB-SUB model or a Observer pattern is best, extension in the form of subscriber registered to publisher works well as subscriber can have their own implementation details abstracting away from core notification service.
Strategy Pattern:
Define a family of algorithms (your types of notifications), encapsulate each one (each type of notification), and make them interchangeable (with a common abstraction). Strategy lets the algorithm vary independently from the clients that use it.
Capture the abstraction in an interface, bury implementation details in derived classes.
Each time you want to add different types of notification you will add new strategies (Twitter, Telegram, ecc)
observer - observable pattern suits for you. if u use any frameworks ( spring in java) built in futures - like event listener & publisher - this really reduces ur burden of implementations.
i hope u r already using frameworks - so research on event listener + publisher. it really solves ur problem ..not only enhancing support to multiple vendors.. it also supports - single - multi thread with less changes.

Using Commands, Events or Services

When designing an application's back-end you will often need to abstract the systems that do things from the systems that actually do them.
There are elements of this in the CQRS and PubSub design patterns.
By way of example:
A new user submits a registration form
Your application receives that data and pushes out a message saying “hey i have some new user data, please do something with this”
A listener / handler / service grabs the data and processes it
(please let me know if that makes no sense)
In my applications I would usually:
Fire a new Event that a Listener is set up to process Event::fire('user.new', $data)
Create a new Command with the data, which is bound to a CommandHandler new NewUserCommand($data)
Call a method in a Service and pass in the data UserService::newUser($data)
While these are nearly exactly the same, I am just wondering - how do you go about deciding which one to use when you are creating the architecture of your applications?
Fire a new Event that a Listener is set up to process
Event::fire('user.new', $data)
Event pattern implies that there could be many handlers, subscribing to the same event and those handlers are disconnected form the sender. Also event handlers usually do not return information to the sender (because there can be actually many handlers and there is a confusion about whose information to return).
So, this is not your case.
Create a new Command with the data, which is bound to a CommandHandler
new NewUserCommand($data)
Commands are an extended way to perform some operation. They can be dispatched, pipelined, queued etc. If you don't need all that capabilities, why to complicate things?
Call a method in a Service and pass in the data
UserService::newUser($data)
Well, this is the most suitable thing for your case, isn't it?
While these are nearly exactly the same, I
am just wondering - how do you go about deciding which one to use when
you are creating the architecture of your applications?
Easy. From many solutions choose only those, which:
metaphorically suitable (do not use events, where your logic does not look like an event)
the simplest (do not go too deep into the depths of programming theories and methods. Always choose solution, that lowers your project development complexity)
When to use command over event?
Command: when I have some single isolated action with few dependencies which must be called from different application parts. The closest analogue is some editor command, which is accessible both from toolbar and menu.
Event: when I have several (at least in perspective) dependent actions, which may be called before/after some other action is executed. For example, if you have a number of services, you can use events to perform cache invalidation for them. Service, that changes a particular object emits "IChangedObject" event. Other services subscribe to such events and respond to them invalidating their cache.

CQRS - can EventListener invoke Command?

I want to use elements of CQRS pattern in my project. I wonder if i do it right with Command and Events.
The thing that I'm not sure is if event can invoke command. To better show what i want to do I will use diagram and example.
This is an example:
User invoke TripCreateCommand. TripCreateCommandHandler do his job and after success publish TripCreatedEvent.
Now we have two listener to TripCreatedEvent (the order of listener execution does not matter)
First listener (can be execute after the second listener):
for each user in trip.author.friends invoke two Command (the order of commands is important)
PublishTripOnUserWallCommand
SendNewTripEmailNotificationCommand
SendNewTripPlatformNotification
Second listener (can be execute before the first listener):
PublishTripOnUserSocials
And this is sample diagram:
Is this a good way ? Can EventListener invoke Command, or maybe I should do it in some other way ?
Your question is about Mesage Driven Architecture which works together with but otherwise unrelated to CQRS.
Anyway, your diagram is almost correct. The event subscriber/handler (I prefer this terminology) can send new Commands via the service bus, but it's not a rule that you should always do this. I implement quite a lot of functionality directly in the event handler, although probalby would be more clean and reliable to send a new command. It really depends on what I want to do.
Note that the message handlers (commands or events) should not know about other handlers. They should know about the bus and the bus takes care of handling. This means that in your app, the event handlers would take the bus as dependency, create the command and send it via the bus. The event handler itself doesn't know what command handler generated the event and can 'reply' to it.
Usually the commands would be handled independently and you can't guarantee the order (unless they're handled synchronously) so maybe you want the second command to be issued as a result of the first command's handling. Indeed, it can be the case for a Saga.
AFAIK you are talking only about doing things synchronously, so your approach works in this case but it's probably not scalable. Moving to async handling will break this execution flow. However your application can be fine with it, not everyhting needs to be twitter.
A message driven architecture is not that straightforward and for some cases (like you want an immediate response from the backend) it's quite complicated to implement, at least more complicated than with the 'standard' approach. So maybe for those particular cases you might want to do it the 'old' way.
If you're worried about decoupling and testing, you can still design the services as they were message handlers but use them directly, instead of a service bus.
Not sure why you would need Commands for performing the updating the information on the user's wall. Why would you choose not to use a View Model Updater for that task.
Sending an email can be considered a Command but could also easily be viewed as just another View Model update.
Not clear on what the purpose of the SendNewTripPlatformNotification is, so I cannot give any suggestions there...
Some of this could also be a candidate for a Saga. Secondly I'm missing your Domain in the diagram, that is what should be responsible for publishing any events, or do you consider the CommandHandler to be the Domain?

Should I use singleton - Http Connection to the server - Iphone App design

So I've been reading about the pros and cons about using Singleton, and I have a scenario which I'm not sure if I should use one, and I thought consulting you guys.
I'm writing an Iphone app which once in a while have to communicate to the server (HTTP) information about the user logged in.
This web service is getting called from different parts of my application.
What I actually need are 2 type of classes:
Responsible for communication with the server - responsible for http setting,the url,header,parameters and etc.
2.classes for each type of web service api - for exmpale UpdateUserInfo Class or SendResults Class. This c
The 2nd class would use the 1st , and all through the app I would need many calles to the 2nd classes.
Should I use Singleton to any of theses ? What is the best way to design it ?
Thanks guys!
Edit:
Example for the 1st class(Let's call it DataDownloader) method would be :
(NSData *) downloadDataWithRequest:(NSURLRequest *)
{
ASIHTTPRequest *dlRequest = [[ASIHTTPRequest alloc] initWithURL:[request URL]];
[dlRequest setTimeOutSeconds:20];
if(retryNum < 1)
retryNum = 1;
[dlRequest setNumberOfTimesToRetryOnTimeout:retryNum];
// and more of the same
}
ASIHTTPRequest is something we're using as an HTTP wrapper.
Now I wouldn't want to call this sequence of function each time I want to send the server an HTTP request, So the option would be to put that inside a dedicated class and create a new instance, or using a singletion.
What I can do for example is Using something like that :
[[UpdateUserInfo sharedInstance] updateInfo:info]
Which can be implemented by setting up a NSURLRequest using the param info , and calling
[[DataDownloader sharedInstance] downloadDataWithRequest:InfoUrlRequest]
Now, assuming the http request are asynchronous , I still can spawn multiple at the same time.
I hope it's clearer now.
What do you think is the best way to design it ?
I wouldn't see the singleton pattern as being a useful solution to the problem you're trying to solve. It's really designed as a technique to control access to a single/finite resource, which isn't meaningfully the case from what I can tell.
For example, is there any reason why you wouldn't permit a user to carry out two network related activities at the same time?
Incidentally, out of interest have you looked at Cocoa classes such as NSURLConnection? I'm not sure you'd need a lower level class to manage the server communications as you're envisaging - this class might suffice. (Had to tell without knowing more about what you're trying to achieve.)
Also don't forget ASIHTTPRequest. It's a full featured network library
http://allseeing-i.com/ASIHTTPRequest/
I usually (and that's personal preference) have one singleton that controls the network management (a singleton and facade pattern in one) as to not having more than the 5 allowed connections. Could be possible for you as well. That would be a singleton for part of your task 1.
But as BobC has already pointed out, ASIHTTPRequest should do everything you need.
Don't reinvent the wheel!
I use the singleton pattern to control access to a web-based API that uses ASIHTTPRequest, and it works very well. ASI uses NSOperationQueues for asynchronous requests, so you don't need to worry about requests clobbering each other.
Because I don't know the order that requests are returned, I sometimes allow my public API methods to supply userInfo dictionaries so my callbacks have some context when they fire.
I would use the Service Locator pattern to obtain each of the services needed in your application. There are a couple different ways to create the service locator. I prefer configuration at initialization over configuration during runtime.
http://en.wikipedia.org/wiki/Service_locator_pattern

Delegation in a NSThreaded Design? (iPhone)

Im using a large amount of very small web services in my app and I have been down a couple of roads that does not scale or work as desired.
The Design approach Im thinking about:
The task for the viewController is to ask for a set of data from a general webServicesClass, this task is started in a new NSThread -> this will instantiate an object which solely retrieves the xml and returns it to the webServicesClass -> the webServicesClass now instantiates an object which solely can Parse some XML coming from this particular web service. The Parser then returns a nice Entity object to the webServiceClass. The WebserviceClass now needs to inform the viewController about this data.
The viewController implements a webServiceClassDelegate and some delegate methods to see if the web service request went as planned. e.g. -(void)aWebserviceFailed and -(void)aWebserviceSuccess.
0.5 Since the WebserviceClass is running is a different NSThread, will it be a problem calling delegate methods on the main NSThread in the parent object?
1.0 I think this design is sound as it completely incapsulates the retrieval, parsing and returning of the Entity in different classes. But, I will have to write delegation methods and implement delegation protocols on each step of the way, for each different webservice. i.e. starting from the bottom, the WebserviceClass must implement delegation methods for both the object that retrieves the XML (start, fail, success), then for the object that parses the XML(start, fail, success) and the WebserviceClass must be able to delegate each of these responses to the viewController that again must implement delegation methods from the WebserviceClass(start, fail, success).
Is there a much simpler way to do this?
I have some design pattern experience, but not from languages that uses delegation so consistently as Objective C. In AS3 or Java I would have events that could bubble up through the objects and inform whoever was listening about changes. In all the Objective example code I have read I have only seen NSNotifications (which would be the equivalent of the AS3 or Java 'Event') used 0.1% of the times.
The Design I described will give me something that scales perfectly for many web services and gives me complete control over where a potential error/exception happens, but it seems to be a lot of code to obtain this loose coupling.
1.1 Or should I fully embrace the delegation approach and get to work:)
Thanks for any pointers or help given. Im not asking for source code or the likes, more a "this is considered best practice in Objective C in the every day situation you just described" :)
I'd recommend taking a look at ASIHttpRequest(obtainable here) and NSOperation + NSOperationQueue (docs here). I don't think you should run a long-lived thread to talk to your web service all the time, unless you absolutely need a constant connection.
Basically ASIHttpRequest and NSOperation both encapsulate all of the networking and threading stuff. Operations make multi-threading on the iPhone really nice. Essentially you create an operation (through a factory or whatnot for ease of use), pop it in a queue and do something with the result.
As for what you do with the result (this applies to your original scenario too and 0.5 and 1.1) what typically happens is your operation/thread will then call a didSucceedAtGettingWhatever or didFailWithError:(NSError*) method. Delegation is pretty much the defacto way of making requests on the phone. If there are multiple delegates, then you can just use subject-observer, like you would in Java.
As for 1.0, ultimately no. What we typically do is we have an OperationDelegate and OperationTypes. Based upon which OperationType succeeded or completed, we have different logic. It's not the greatest and there are a ton of different ways of doing this, but you will have to have separate logic for separate events regardless of what you do. Whether or not that's in one method or many methods is up to you.