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.
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.
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.
- Alex Arnell's inheritance.js is a short and sweet chunk of code that makes JavaScript act OO, complete with access to the parent 'Class'.
- Here's one of John Resig's solutions to the same problem: http://ejohn.org/blog/simple-javascript-inheritance/.
- Chapter 16 of Programming in Lua describes object orientation in Lua. Specifically, section 16.2 gives a nice example of inheritance.
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.
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.