Friday, December 4, 2009

Objective-C

The choice of NEXT (and by extension Apple) to use Objective-C is largely a matter of timing. Java and C# are both derived from C++, but Objective-C has no relation to C++. Stroustrup published his first book on C++ in 1985, the same year Jobs left Apple to start NEXT. At the time, there was, of course, no way of knowing which object-oriented language would become dominant. C++ compilers were not widely available until about 1992.


Fortunately, since Objective-C is also an extension of ANSI C, the syntax is familiar until you get to the object-oriented extensions, but at this point it is, in the words of one blogger, Alan Storm, “deeply, deeply weird”. The syntax for declaring a class and it's “messages” (instead of methods or member functions) is one of the weird things. Here is an example from the GNUstep manual (with comments stripped out).


#include

#include


@interface Test

+ (const char *) classStringValue;

@end


@implementation Test

+ (const char *) classStringValue;

{

return "This is the string value of the Test class";

}

@end


int main(void)

{

printf("%s\n", [Test classStringValue]);

return 0;

}


(This code goes in a file source.m.)


C++ basically duplicated the syntax of a struct in C and added member functions. In fact, if memory serves (it's been years since I've written any C++) you can have member functions in a C++ struct as if it is a class. Then Java got rid of the structs and just has classes. Objective-C took a different route entirely, adding syntax that frankly looks very out of place with the rest of the language. The @ reminds me of annotations in Java.


Not only is the syntax different but the message passing mechanism behaves differently. “The Call vs. Message Sending semantics seem, on the surface, to be the same thing, but my book has promised me there are subtle, yet deeply important differences. The first I’ve encountered is, an object will accept messages that haven’t been defined (it silently ignores them) whereas Java/C#/PHP5 would yell at you for calling an undefined method.” [Alan Storm] Objective-C is also more forgiving if you try to use a null (nil) object.


No comments:

Post a Comment