views:

562

answers:

3

Steve Yegge recently posted an interesting blog post on what he calls the universal design pattern. In there he details using prototypes as a modelling tool, instead of classes. I like the way this introduces less coupling compared to inheritance. But that is something one can get with classes as well, by implementing classes in terms of other classes, instead of inheritance. Does anyone else have success stories of using prototypes, and can maybe help explain where using prototypes is advantageous compared to classes. I guess it comes down to static modelling versus dynamic modelling, but more examples would be very welcome.

+3  A: 

Prototypes are a form of inheritance, it's just that objects inherit attributes and behavior directly from other objects, instead of getting their attributes and behavior from their class, which inherits from other classes.

For examples, check out any object oriented code in a prototype based language like, for example, JavaScript.

Glomek
you have it backwards: OOP class-based inheritance is a subset of prototyping (which is a subset of duck typing)
Javier
I think you misinterpret me. I was saying that prototypes are one form of inheritance and class/subclasses are another form. I was not trying to get into the whole "which one can be implemented in terms of the other" question.
Glomek
+6  A: 

One interesting bit is that it's easy to make a prototype-based language act OO but it's difficult to make an OO language act prototype-based.

It's not entirely clear what OO as prototype would look like, aside from composition versus inheritance as you mention.

A prototype language makes complex inheritance behavior easy. You can implement multiple inheritance, mixin-like behavior, or just pick and choose what you want from one object to add to another.

Wikipedia's article mentions: "Advocates of prototype-based programming often argue that class-based languages encourage a model of development that focuses first on the taxonomy and relationships between classes. In contrast, prototype-based programming is seen as encouraging the programmer to focus on the behavior of some set of examples and only later worry about classifying these objects into archetypal objects that are later used in a fashion similar to classes."

That's not to say the prototype paradigm is all pros and no cons. If OO is more restrictive, it's because it chooses to be. I can see where all that flexibility might get you into trouble if you aren't careful.

Corbin March
+1  A: 

For those interested, NewtonScript was (is) a dual language: you had prototypes and you had classes. You could choose whether to inherit from a class, from a prototype or from both.

CesarGon