Per Ola Kristensson | Blog

Blog
Publications
Software
Other Stuff

Archive for the ‘teaching’ Category

Using Objective-C to teach object-oriented programming?

Monday, September 6th, 2010

I am programming in Objective-C right now. It is an interesting programming language, essentially a smaller and simpler alternative to C++. However, unlike C++, Objective-C is a strict superset of ANSI C, which means any valid C code can be compiled by an Objective-C compiler, something that a C++ compiler cannot guarantee (for instance, the need to cast void-pointers is different in C and C++).

What Objective-C does is add additional well-needed abstractions to ANSI C, such as classes, interfaces and inheritance. I have to admit, coming from mostly C and Java programming, I was initially annoyed by the Smalltalk-inspired syntax (and I’m still not convinced it makes any sense).

However, I am starting to think that Objective-C might be a good teaching language for an ambitious programming class. Unlike Java and C++, Objective-C’s syntax clearly differentiates between standard function calls and instance method invocations (message expressions). The syntax also differentiates between method declarations and function declarations.

The theory is that by having distinct syntax for these and other aspects of the programming language the learner is forced to conceptualize the differences. Syntax is enforced by the compiler and conceptual misunderstandings will lead to compilation errors that the learner has to correct. In other words, conceptual misunderstandings are explicitly pointed out to the learner by the compiler. If the learner does not satisfy the compiler the program won’t compile, let alone run. For example, the Objective-C syntax makes it impossible to call an instance method and not realize that this is message passing and not a static function invocation.

Another potential advantage of using Objective-C as a teaching language is that it is somewhere in the middle between Java and C++. It is closer to the hardware than Java. For instance, when an object is created in Objective-C, the idiom is to first explicitly allocate memory for it and thereafter initialize it (e.g. the expression UIButton *button = [[UIButton alloc] init]; first allocates memory for a structure to represent the button, and then initializes it). This first step of allocation and memory management is hidden for Java programmers. However, computer science students obviously need to understand memory management. Yet Objective-C is not as convoluted as C++. For instance, it doesn’t have operator overloading, templates and multiple inheritance. Hence it is not too daunting for the beginning programmer.

This tutorial succinctly highlights the differences between Objective C and C.