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’ ?
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.
4