Friday, February 03, 2006

Teaching Interfaces

A recent comment on Toxi's blog asked about techniques for teaching novice programmers about interfaces, in the context of the Processing development environment. My approach starts by taking a step back from Java's OO biases, and asking about interfaces in general. Contrary to Sun's marketing, interfaces are not best understood as a gentler version of C++'s multiple inheritance. Instead they are a language construct for explicitly representing an object's Contract. A class implementing an interface is guaranteed to provide "at least" a certain sort of behavior, by which we mean "methods."

Considered as a syntax for specifying class contracts, we've found a decent metaphor for teaching: It is quite natural for students to understand the necessities of Contract, and even to understand interfaces as a restriction on "freedom." An object is free to behave in any way it likes, as long as it does at least X, Y, and Z... Three behaviors the rest of the world is expecting of the object.

Please forgive my blurring of "class" and "object" above. This reveals another of my software writing biases, this time for prototype-based languages. Here even my cherished Ruby falls short. Prototype-based languages make no distinction between "classes" and "instances." Everything is just an "object." Create a new object by cloning a already-existing one, and then customize its behavior by dynamically adding methods and data. It is the context of how an object is used that determines its "abstract-ness." If one only ever clones an object but doesn't use it, that object is effectively an abstract class.

While prototype-based design can be quite a leap for OO programmers accustomed to the C++/Java way of doing things, it is actually quite easy to teach novices. Since prototype objects are closer simulacra for physical objects, we needn't use such stretched teaching metaphors. No more "classes are blueprints," and "instances are houses."

Imagine being able to shrug off awkward explanations of both the static keyword and the new operator, without any significant loss in elegance or expressiveness. I would love to see Processing do prototype-based OOP.

1 Comments:

At 3:24 PM, Blogger Tom Carden said...

Yeah, contracts are a great way to think about interfaces. I'm Comparable, so I promise to have a working compareTo method, for example.

 

Post a Comment

<< Home