Friday, March 14, 2008

Nice things about ObjC

Title linkies to a post by an F-Script guy (the F-Script guy? I'm not sure, I don't really follow F-Script development) about nice things he likes about the Objective-C language. Remembering that he wrote a Smalltalk scripting environment for Cocoa, some of the list is fairly unsurprising, much is made of the dynamic runtime, multiple-level dispatch and so on. I think the article is mainly bang on, though I do disagree with the author in a few places. The next paragraph is not one of those places.


Classes are objects. ++ This is the coolest thing ever about proper object-oriented languages, and one of my strongest arguments for design patterns are not language independent. Do patterns such as Prototype need to exist in ObjC code, when the Factory Method +new will give you an unconfigured typical instance?


Dynamic typing... Optional static typing. This is one of those slippery slopes where both edges are sharp enough to give you the rope required to shoot yourself in the foot. Duck typing (i.e. if an object looks like a duck, and quacks like a duck...) is useful in some cases and damned annoying in others. To avoid runtime exceptions with duck typing you either have to [i]mentally assert correctness in your code, [ii]perform all the runtime introspection needed to ensure your messages will be handled, or [iii]eschew the duck type completely and downcast to either an instance of a class or a conformant of a protocol (or both; you could do something like GLModelObject <NSCoding> * if you really felt like it). Another issue with the ObjC implementation of duck typing is that it doesn't always work as you'd think. When it does work, it's very powerful - when it doesn't, you probably won't find out until runtime, and could be spending a long while working out what happened.


Categories. No, afraid not. Nice idea, badly implemented. The point of categories is to let you decorate a class with additional functionality by adding methods - currently not ivars - in additional code objects, not all of which need be present at launch. This lets you work around the visibility contract of the class (can't see an @private ivar? Just chuck an instance method in!), though in fairness so does KVC. But perhaps the worst crime a category can commit is killing someone else's category. Or overwriting an "undecorated" method.


I still love Objective-C, mainly because I love Cocoa and GNUstep and making code that works like them, it's definitely powerful and fun too. But it's not without its rough edges and sharp spiky bits.

No comments: