19 October 2007

Inheritance is over-rated

Some more observations based on my experiences with EcmaScript (a.k.a. Javascript) as compared to C++ and Java:

(I suppose I could try to generalize and consider EcmaScript a representative of the Smalltalk tradition versus C++ and Java as representatives of the Simula tradition; but that probably opens a lot of other issues.)

It occurs to me that most classes I’ve written in C++ or Java have not needed inheritance. They provided only encapsulation. (Which I can do just fine in C—no object-orientation required.)

When I have needed inheritance, it has most often been for polymorphism. In EcmaScript, you don’t need inheritance for polymorphism.

(With C++, you can have polymorphism without inheritance, but that requires the complexity of templates. Likewise, in Java you can use reflection to achieve the same sorts of things, but you get more complexity with it.)

Sometimes I’ve abused inheritance in C++ or Java to work around limitations. Such as adding additional methods to an existing class. In EcmaScript, I can add methods to objects (or objects serving class-like roles) directly.

In EcmaScript, I only really need to use inheritance when I need to share an implementation, and that just doesn’t seem to come up as often in my experience.

(Moreover, I find closures—which EcmaScript has but C++ and Java lack—extremely useful.)

Now, there are—of course—trade-offs involved. EcmaScript isn’t all roses by any means. Give it a static debugger (like MrSpidey/MrFlow), and I think it could hold its own versus C++ or Java for many applications.

Give it hygienic macros (on the road-map for Javascript 3) and first-class continuations, and it starts to stack up well against Scheme as well.

No comments: