Duck Typing in Objective C / Cocoa
July 15th, 2009 RustyI discovered, quite by accident, that Objective C supports a feature I have been yearning for in .net / C#. While dynamic languages such as Ruby and Python (I’m no expert and could be wrong but I believe this to be true) allow you to pass very loosely typed objects around and swap one type for another, strongly typed languages usually do not allow this. DotNet takes it a step further and won’t even allow you to inherit and override unless the author of the subclass explicitly marked the property or method as virtual. This rears its ugly head when you try to mock for unit testing, a very valuable practice, and it won’t let you because the class you intend to mock was not littered with virtual decoration. What this means to me is that I will, from now on, always mark my props and methods virtual. That’s just ugly and unnecessary. I would have preferred sealed to have been the exception and virtual to be the default. Oh well.
If it quacks like a duck…
In objective c, take the following class
@interface Lead : NSObject {
NSString *nameFirst;
}
@property (retain, nonatomic) NSString *nameFirst;
@end
The implementation is irrelevant . If I have a consumer of this class like so:
@class Lead;
@interface StateManager : NSObject {
Lead *currentLead;
}
@property (retain, nonatomic) Lead *currentLead;
…and let’s say I did something with the nameFirst method in my StateManager.
I could do this
@interface Giraffe : NSObject {
NSString *nameFirst;
}
@property (retain, nonatomic) NSString *nameFirst;
@end
and pass it in to the StateManager
Giraffe *giraffe = [Giraffe new];
[giraffe setNameFirst:[textFieldName text]];
StateManager *stateManger = [StateManager getSingleton];
[stateManger setCurrentLead:giraffe];
Other than a compiler warning, all is well. No errors will occur. Iff you want to get rid of the compiler warning, cast the giraffe
[stateManger setCurrentLead:(Lead *)giraffe];
Which, apparently, in Objective C is more of a, “yes, I know that’s supposed to be a Lead instance,” rather than any real cast.
So, in review, you have object oriented features but not strongly typed restrictions. This makes the opportunities endless and probably scares the hell out of some paranoid security software engineers but I’d rather have open frameworks and defensive programming than defensive frameworks and less power and flexibility.