in my application, I have a request type associated with variety of API calls I make to the REST server. when the response from server comes in the same delegate method for web engine's response,
I have to check the API type in the request object passed as a parameter to the delegate method and then take the corresponding action. The problem is there are around 10-12 different API request types. So the switch case that checks the different enums associated with API Types, takes action based on it.
How to get rid of this switch 'tower' ?
1 Answer 1
In Objective-C you can build selectors at runtime. This lets you "stringly-type" method dispatch, which removes a lot of conditional code (though replaces it with something that has its own problems). An example that shows how this might work:
- (void)sendHTTPRequest: (NSString *)request
{
NSString *requestMethod = [NSString stringWithFormat: "send%@Request", [request upperCaseString]];
SEL requestSelector = NSSelectorFromString(requestMethod);
if ([self respondsToSelector: requestSelector])
[self performSelector: requestSelector];
else
[self reportUnknownRequest: request];
}
- (void)sendGETRequest { ... }
- (void)sendPOSTRequest { ... }
- (void)sendDELETERequest { ...}
- (void)reportUnknownRequest: (NSString *)request { ... }
I use this approach for building parsers, for avoiding large switch statements, and for behaviour that depends on the class of a parameter in cases where putting the behaviour on the parameter classes would not be appropriate.
-
my classification was in terms of request type as say, user-profile,comments,article etc. the APIType is an enum for each of these that I check when I get a response for my request. Many cases they all are response of a GET request only. but I still have to check what I was asking from the server.Amogh Talpallikar– Amogh Talpallikar2013年01月11日 16:21:21 +00:00Commented Jan 11, 2013 at 16:21
-
I don't know objective-c, but this is pretty cool. I'm a fan of the idea of message-passing style OO for exactly abstractions like this which you get from dispatch invocation instead of direct method-calling invocations of C++/java/C# style OO.Jimmy Hoffa– Jimmy Hoffa2013年01月11日 16:23:47 +00:00Commented Jan 11, 2013 at 16:23
-
Oh.. I got the whole idea.. instead of enums, if we have striings to selectors then same piece of code works, and we can separate out code by methods. Another idea I was thinking was of having callback, blocks in dictionaries.Amogh Talpallikar– Amogh Talpallikar2013年01月11日 17:26:58 +00:00Commented Jan 11, 2013 at 17:26
-
Yes @amogh, or you could map your enumerated type to selectors.user4051– user40512013年01月12日 05:02:02 +00:00Commented Jan 12, 2013 at 5:02
Explore related questions
See similar questions with these tags.