Data provider calling a delegate: specifics or generic? - objective-c

I have a XML parser which will parse 17 different XML documents (I'm simplifying this).
When the parser has finished its job, it calls the object that did the request.
First way
A single method that looks like
- (void)didReceiveObject:(NSObject *)object ofType:(MyObjectType)type
with MyObjectType being an enum.
In this method, I check the type and redirect the object to the corresponding method.
Second way
There is a callback method for each of the 17 types of object I can receive.
- (void)didReceiveFoo:(MYFoo *)foo
- (void)didReceiveBar:(MYBar *)bar
... and so on
Which way of using delegates will be better?
We had a discussion about this with a colleague and couldn't find one way more appealing than another. It seems like it's just deciding what method to call from the parser or within the delegate....
Even when thinking about adding future methods/delegates callbacks, we don't see any real problem.
Is one of these ways better than the other? Is there another way?

Why not go with
- (void)didReceiveObject:(NSObject *)object
and then inspect the class type?
This seems cleaner and more extensible to me, because it means you can parse other objects in the future without adding more callbacks.
(I know this is the same as option one, but I wanted to point out that your second argument was unnecessary.)

First method:
Pros:
More flexible to future changes.
Cons:
May result in a large switch statement or messy if ... else if ... else statement.
Probably results in a series of explicit methods anyway.
Requires type cast.
Second method:
Pros:
No type casting.
If methods are optional, delegate is only bothered with the objects it's interested in.
Cons:
If methods are not optional and the interface is expanded later, all delegates will have warnings until the new methods are implemented.
If methods are not optional, this can be a lot of methods to implement for every delegate.
Generally when building delegate interfaces I lean towards generics for future extensibility. Changing an API, especially with open source code, can be very difficult. Also, I don't quite understand why you have one XML parser doing so much. You may want to consider a different design. 17 different XML documents seems like a lot. That aside, I'll propose a third method.
Third method:
Create a dictionary that maps strings to blocks. The blocks would probably be of type void(^BlockName)(id obj). Your parser would define a series of strings that will be the keys for your various blocks. For example,
NSString * const kFooKey = #"FooKey";
NSString * const kBarKey = #"BarKey";
// And so on...
Whoever creates the XML parser would register a block for each key they are interested in. They only need to register for the keys they are interested in and it's completely flexible to future change. Since you are registering for explicit keys/objects, you can assert the passed in type without a type cast (essentially Design By Contract). This might be over kill for what you want, but I've found similar designs very beneficial in my code. It combines the pros of both of your solutions. It's main downfall is if you want to use an SDK that doesn't have blocks. However, blocks are becoming a de facto standard with Objective-C.
On top of this you may want to define a protocol that encompasses the common functionality of your 17 objects, if you haven't done so already. This would change your block type to void(^BlockName)(id<YourProtocol> obj).

Here's the decision.
We will implement both and see which way is the more used.
The first way is the easiest and fastest so we will keep it for internal needs.
But we may be shipping this code as a static library so we want to give the minimal amount of information. So we will also stick with the with the second way.
As there should be a big chunk of code for each callback, the generic way will certainly be the big switch statement rbrown pointed.
Thank you for your help.

Related

Is using C functions instead of static methods for making pure functions a bad design?

If I am implementing a function that does some calculation based on certain input and returns the output without causing any side effects.
I always use Regular C functions instead of having static methods in a class.
Is there a rationale behind using static methods forcefully put into a class ?
I am not talking about methods that create singletons or factory methods but the regular methods like there:
Instead of having something like this:
+(NSString *)generateStringFromPrefixString:(NSString *)prefixString word:(NSString *)word;
won't this be better ?
NSString *generateString(NSString *prefixString, NSString *word);
In terms of efficiency also, wont we be saving, lookup for the selector to get the function pointer ?
Objective-C doesn't have such a thing as "static methods". It has class methods. This isn't just picking a nit because class methods are dispatched dynamically, not statically. And that can be one reason to use a class method rather than a function: it allows for subclasses to override it.
By contrast, that can also be a reason to use a function rather than a class method – to prevent it from being overridden.
But, in general, there's no rule that you have to use class methods. If a function suits your needs and your preferences, use a function.
I don't think it is bad design, no, but there are certain circumstances where one may be considered more appropriate than the other. The key questions are:
Does this method belong to a class?
Is this method worth adding to a class?
A class is something that is self-contained and reusable. For the method in your example, I would be tempted to answer "Yes, it does/is," because it is something specific to NSString and is a method you (presumably) want to use fairly often. Its parameters are also of type NSString. I would therefore use the message form in a class extension and #import the extension when you need it.
There are two situations (off the top of my head) where this is not really appropriate. Firstly is the situation where the method interacts specifically with other entities outside of the 'main class'. Examples of this can be found near the bottom of Apple's NSObjcRuntime.h file. These are all standard C functions. They don't really belong to a specific class.
The second situation to use a standard C function is when it will only be used once (or very few times) in a very specific circumstance. UIApplicationMain is the perfect example, and helper methods for a specific UIView subclass's -drawRect: method also come to mind.
A final point on efficiency. Yes, selector lookup is fractionally slower standard C calls. However, the runtime (Apple's at least, can't comment on GCC's) does use a caching system so that the most commonly sent messages quickly gravitate to the 'top' of the selector table.
Disclaimer: This is somewhat a question of a style and the above recommendations are the way I would do it as I think it makes code more organised and readable. I'm sure there are other equally valid ways to structure/interleave C and Objective-C code.
One important factor is testability. Does your c-functions specifically need testing? (off-course everything has to be ideally tested, but sometimes you just can test a thing by calling what calls it). If you need to, can you access those functions individually?
Maybe you need to mock them to test other functionality?
As of 2013, if you live in the Apple/Xcode/iOS/MacOS world, it is much more likely you have more built-in tools for testing things in objc than plain c. What I am trying to say is: Mocking of c-functions is harder.
I like very much C functions. At first I didn't like them to be in my good-looking objc code. After a while, I thought that doesn't matter too much. What it really matters is the context. My point is (as same as PLPiper's on NSObjcRuntime.h) that sometimes, by judging by its name or functionality, a function does not belong to any class. So there is no semantic reason to make them a class method. All this ambiguous-like thing went away when I started writing tests for code that contained several inline c functions. Now, if I need some c function be specifically tested, mocked, etc. I know it is easier to do it in objc. There are more/easier built-in tools for testing objc things that c.
For the interested: Function mocking (for testing) in C?
For sake of consistency and programmer expectation, i'd say to use Objective C style. I'm no fan of mixing calling notation and function notation, but your mileage may differ.

Downsides about using interface as parameter and return type in OOP

This is a question independent from languages.
Conceptually, it's good to code for interfaces(contracts) instead of specific implementations. I've got no problem understanding merits about the practice.
However, when I really code in that practice, the users of my classes, from time to time need to cast the interfaces for specific needs of specific functions provided by specific classes that implement that interface.
I understand there must be something wrong, either on my side or on the user's side, as the interface should expose all methods/properties(in the case of c#) that can possibly be necessary.
The code base is huge, and the users are clients.
It won't be particularly easy to make changes on either side.
That makes me wonder some downsides about using interface as parameter and return type.
Can people please list demerits of the practice? And please, include any solution if you know how to work around it.
Thanks a lot for enlightening me.
EDIT:
To be a bit more specific:
Assume we have a class called DbInfoExtractor. It has a public method GetInfo, as follows:
public IInformation GetInfo(IInfoParam);
where IInformation is an interface implemented by specific classes like VideoInfo, AudioInfo, TextInfo, etc; IInfoParam is an interface implemented by specific classes like VidoeInfoParam, AudioInfoParam, TextInfoParam, etc;
Apparently, depending on the specific object passed into the method GetInfo, the DbInfoExtractor needs to take different actions, as it is reasonable to assume that for different types of information, the extractor considers different sets of aspects(e.g. {size, title, date} for video, {title, author} for text information, etc) as search keys and search for relevant information in different ways.
Here, I see two options to go on:
1, using if ... else ... to decide what actually to take depending on the type of the parameter the GetInfo method receives. This is certainly bad, as avoiding this situation is one the very reasons we use polymorphism.
2, We should call IInfoParam.TakeAction(), and each specific implementation of IInfoParam has its own TakeAction() method to actually search and find the corresponding information from the database.
This options seems better, but still quite bad, as it shouldn't be the parameter that takes action searching and finding the information; it should be the responsibility of DbInfoExtractor.
So how can I delegate the TakeAction back to DbInfoExtractor? (I actually wrote some code to do this, but it's neither standard nor elegant. Basically I make parameter classes nested classes in DbInfoExtractor, so that they can call various versions of TakeAction of DbInfoExtractor.)
Please enlighten me!
Thanks.
Thanks.
Why not
public IVideoInformation GetVideoInformation(VideoQuery);
public IAudioInformation GetAudioInformation(AudioQuery);
// etc.
It doesn't look like there's a need for polymorphism here.
The query types are Query Objects, if you need those. They probably don't need to be interfaces; they know nothing about the database. A simple list of parameters (maybe just ID) might be sufficient.
The question is what does the client have, and what do they want? That's your interface.
Switch statements and casting are a smell, and typically mean that you've violated the Liskov substitution principle.

objective-c block vs selector. which one is better?

In objective-c when you are implementing a method that is going to perform a repetitive operations, for example, you need to choice in between the several options that the language brings you:
#interface FancyMutableCollection : NSObject { }
-(void)sortUsingSelector:(SEL)comparator;
// or ...
-(void)sortUsingComparator:(NSComparator)cmptr;
#end
I was wondering which one is better?
Objective-c provides many options: selectors, blocks, pointers to functions, instances of a class that conforms a protocol, etc.
Some times the choice is clear, because only one method suits your needs, but what about the rest? I don't expect this to be just a matter of fashion.
Are there any rules to know when to use selectors and when to use blocks?
The main difference I can think of is that with blocks, they act like closures so they capture all of the variables in the scope around them. This is good for when you already have the variables there and don't want to create an instance variable just to hold that variable temporarily so that the action selector can access it when it is run.
With relation to collections, blocks have the added ability to be run concurrently if there are multiple cores in the system. Currently in the iPhone there isn't, but the iPad 2 does have it and it is probable that future iPhone models will have multiple cores. Using blocks, in this case, would allow your app to scale automatically in the future.
In some cases, blocks are just easier to read as well because the callback code is right next to the code that's calling it back. This is not always the case of course, but when sometimes it does simply make the code easier to read.
Sorry to refer you to the documentation, but for a more comprehensive overview of the pros/cons of blocks, take a look at this page.
As Apple puts it:
Blocks represent typically small, self-contained pieces of code. As such, they’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished.
Blocks are a useful alternative to traditional callback functions for two main reasons:
They allow you to write code at the point of invocation that is executed later in the context of the method implementation.
Blocks are thus often parameters of framework methods.
They allow access to local variables.
Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.
On this page
The one that's better is whichever one works better in the situation at hand. If your objects all implement a comparison selector that supports the ordering you want, use that. If not, a block will probably be easier.

Objective-C: Blocks vs. Selectors vs. Protocols

I frequently find myself writing "utility" classes that can be re-used throughout my projects.
For example, suppose I have an "Address Book" view. I might want to use my address book to select who gets sent an email, or maybe who gets added to a meeting request.
I'd develop this view controller so it can be used by both the email controller, and the meetings controller, with some sort of callback mechanism to let the caller know the user either finished selecting someone from the address book, or they canceled.
It seems there are basically four (reasonable) approaches one might take in this scenario;
Create an "AddressBookDelegate" protocol and a corresponding delegate property on the AddressBookController. Then use the messages defined in the protocol to communicate the result (similar to UIActionSheetDelegate).
Create an "informal" "AddressBookDelegate" protocol and a corresponding delegate property on the AddressBookController, but the type of the delegate property will be "id", and will check at runtime with "respondsToSelector:" to see if the delegate implements the methods we require (seems like most of the framework stuff has started going this way).
Pass the AddressBookController an id that represents a delegate, as well as two SELs which specify the methods to call when the user selects a user or cancels the request. The benefit I see with this is; suppose one controller supports BOTH sending emails AND setting up meetings (I know in this example that seems like bad design... but one can imagine a more generic situation where this would seem perfectly reasonable for a utility class) - In this case you could pass the AddressBookController different SELs depending on whether you're adding users to an email, or adding users to a meeting... a huge improvement over an iVar to indicate the controller's "state".
Pass the AddressBookController two blocks; one to run when the user selects someone from the address book, and one to run if the user cancels the request.
The blocks have been so tremendously useful to me, and SO much more elegant, I'm finding myself almost confused over when to NOT use them.
I'm hoping more experienced members of the StackOverflow community than I can help out with their thoughts on this topic.
The 'traditional' way to do this is with a protocol. Informal ones were used before #protocol was added to the language, but that was before my time and for at least the last few years informal protocols have been discouraged, especially given the #optional specifier. As for a 'delegate' which passes two SELs, this just seems more ugly than declaring a formal protocol, and generally doesn't seem right to me. Blocks are very new (esp. on iOS), as these things go, and while we have yet to see the tremendous volume of documentation/blogs on the best tried and true style, I like the idea, and this seems to be one of the things blocks are best for: neat new control flow structures.
Basically what I'm trying to say is that each of these methods vary in age, with none being better than the last except for style, which obviously counts for an awful lot, and is ultimately why each of these things was created. Basically, go with the newest thing you feel comfortable with, which should be either blocks or a formal protocol, and that your confusion is most likely coming from reading conflicting sources because they were written at different times, but with time in perspective, it is clear to see which supersedes the others.
[Controller askForSelection:^(id selection){
//blah blah blah
} canceled:^{
//blah blah blah
}];
is probably a hell of a lot more concise than defining two extra methods, and a protocol for them (formally or otherwise) or passing the SELs and storing them in ivars, etc.
I would just go with your first approach. It's a tried and true pattern in Cocoa, and seems to fit very well into what you're doing.
A few comments on the other approaches:
Informal protocol - I don't really see any advantage of doing this over a formal protocol. Every since formal protocols gained #optional methods, the utility of informal protocols is much less.
Passing SELs - I don't think this is an established pattern in Cocoa. I personally wouldn't consider it as better than the delegate approach, but if it fits your thinking better, then go for it. You're not really getting rid of state; you're just transforming into something else. Personally, I'd prefer to have an ivar that I can set and check without having to use selector types.
Passing blocks - This is sort of a new-age approach, and it has some merit. I think you need to be careful though because, in my opinion, it doesn't scale really well. For example, if NSTableView's delegate and data source methods were all blocks, I would personally find that somewhat annoying. Imagine if you wanted to set 10 different blocks, your -awakeFromNib (or whatever) method would be pretty big. Individual methods seem more appropriate in this case. However, if you're sure that you're never going to go beyond, say, two methods, then the block approach seems more reasonable.

Objective-C wrapper API design methodology

I know there's no one answer to this question, but I'd like to get people's thoughts on how they would approach the situation.
I'm writing an Objective-C wrapper to a C library. My goals are:
1) The wrapper use Objective-C objects. For example, if the C API defines a parameter such as char *name, the Objective-C API should use name:(NSString *).
2) The client using the Objective-C wrapper should not have to have knowledge of the inner-workings of the C library.
Speed is not really any issue.
That's all easy with simple parameters. It's certainly no problem to take in an NSString and convert it to a C string to pass it to the C library.
My indecision comes in when complex structures are involved.
Let's say you have:
struct flow
{
long direction;
long speed;
long disruption;
long start;
long stop;
} flow_t;
And then your C API call is:
void setFlows(flow_t inFlows[4]);
So, some of the choices are:
1) expose the flow_t structure to the client and have the Objective-C API take an array of those structures
2) build an NSArray of four NSDictionaries containing the properties and pass that as a parameter
3) create an NSArray of four "Flow" objects containing the structure's properties and pass that as a parameter
My analysis of the approaches:
Approach 1: Easiest. However, it doesn't meet the design goals
Approach 2: For some reason, this seems to me to be the most "Objective-C" way of doing it. However, each element of the NSDictionary would have to be wrapped in an NSNumber. Now it seems like we're doing an awful lot just to pass the equivalent of a struct.
Approach 3: Seems the cleanest to me from an object-oriented standpoint and the extra encapsulation could come in handy later. However, like #2, it now seems like we're doing an awful lot (creating an array, creating and initializing objects) just to pass a struct.
So, the question is, how would you approach this situation? Are there other choices I'm not considering? Are there additional advantages or disadvantages to the approaches I've presented that I'm not considering?
I think that approach 3 would be the preferred way to do things. When you wrap a library you'll want to create wrappers around any object or structure that the user is expected to deal with.
If you wrap everything, then you are free to change the internal workings of your classes at a later date without affecting the interfaces that your users have become accustomed to. For example, in the future you may realize that you'd like to add some type of error checking or correction... maybe setting a stop that is earlier than the start causes some calculation errors, you could change the stop method in your Flow wrapper to set start equal to stop if stop is less than start (I admit, that's a really bad example).
I'd stick with approach 3. You're "just passing a struct" now, but the Flow object might expand more in the future. You say speed is not an issue and so I'd imagine memory consumption isn't either, or you would be sticking with C anyway.
My answer is not what you were asking, but it is still how I "would approach the situation".
The first question I would ask is, "what value does this wrapper add?" If the answer is, "to use Objective-C syntax" then the answer is "don't change a thing, use the library as-is because C is Objective-C syntax."
I don't know which library you are wrapping, so I'll use SQLite for an off the top of my head example. Using a layered approach, I would do something like this:
A) High level objects (Order, Customer, Vendor...)
B) Base class (Record)
C) SQLite
So the base class is written to call SQLite directly then the other classes work as regular Objective-C classes.
This is apposed to:
1) High level objects (Order, Customer, Vendor...)
2) Base class (Record)
3) SQLite Wrapper (Objective-C)
4) SQLite
The same application is created but there is extra work creating, maintaining and debugging level 3 with very little to show for it.
In the first version, layer B wrapped SQLite so nothing above it called SQLite directly AND it didn't try to provide all of SQLite functionality. It just provides the functionality that layer A needs and uses SQLite to achieve what is needed. It 'wraps' SQLite but in a more application specific manner. The same Record class could be reused in another application later and extended to meet the needs of both applications at that time.
Since Objective-C uses structures, why not leave it as a struct like NSRect?