CSC/ECE 517 Fall 2010/ch4 4e ms: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(200 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<p style="font-size:25px">  <b>Prototype Based Programming</b> </p>
<p style="font-size:25px">  <b>Prototype Based Programming</b> </p>


Most of the  object-oriented programming languages at present are class based. All objects of a certain class share the same properties. Modelling these classes into real-world objects exhibit certain limitations. Class based languages are too rigid to even  define simple concepts in terms of shared properties, like traffic jams or the greenhouse effect.
''"Objects in the real world have only one thing in common: they are all different"''
''(anonymous, A. Taivalsaari, JOOP, Nov. 1997)''


==Introduction==
==Introduction==
Prototype based programming is an object oriented programming methodology. Its main characteristic feature is that no classes are present in the language constructs. Behavior reuse or inheritance function is performed by cloning some prototype objects. Thus known as instance-based programming or class-less based programming and such languages are known as prototype based languages.
Prototype based programming is an [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented programming] methodology. It differs from the other classes of object oriented languages due to its main characteristic feature that no classes are present in the language constructs. Behavior reuse or inheritance is performed by cloning some instance or prototype objects. Thus, it is also known as 'instance-based programming' or 'class-less based programming' and such languages are known as 'prototype based languages'.


Objects used in prototype based programming are referred as ''Prototypes'', which resemble an instance of class in class-based programming. You can add or remove variables and methods at any level of a single object, without worrying if the object still fits in the system. New objects are created by copying existing objects, which is called as ''cloning''.
Objects used in prototype based programming are referred as ''prototypes'', which resemble an instance of a class in [http://en.wikipedia.org/wiki/Class-based_programming class-based programming]. It differs from a class instance as one can add or remove variables and methods at any level of a single object, without worrying if the object still fits in the system. Typically, new objects are created by copying existing objects, which is called as ''cloning''.
 
Object Oriented programming languages are classified based on following criteria:
* Class based : Object instances are created fro skeleton or blueprint of the class.
* Prototype based : Object instances are created from concrete examples and other objects are created with such a prototype reference.
* [http://en.wikipedia.org/wiki/Automata-based_programming Automata based] : The program is thought of as a model of a finite state machine or any other formal automata.
* Based on separation of concerns e.g. aspect oriented languages
 
The figure below shows where prototype based languages fit in the broad classification of object oriented languages.
<center>
[[Image:oops.jpg]]
</center>
 
Since prototype based languages do not distinguish between classes and instances, there is the concept of just objects. There are three types of objects- normal objects, prototypes and traits. Prototypes and traits are not real objects but the term object is loosely used to signify their specialization feature. Normal objects are used to represent the local state. Prototypes are blueprints to generate clones. Traits, if used in the programming language, are abstract descriptions of objects that do not possess a state i.e. only provides a set of methods. Traits are never cloned or used directly and are intended only to be used as the shared parents of normal objects. [1]


==History==
==History==
* Eleanor Rosch first introduced the 'Prototype Theory' in mid-1970's. Rosch proposed that to classify objects, one can match them against a "prototype" i.e. an ideal example which exhibits the most representative features of the category of objects. This evolved the concept of frame based languages that used the prototype theory in the field of knowledge representation languages. Here, frames were used to represent knowledge like typical values, default values, or exceptions.
* Eleanor Rosch first introduced the 'Prototype Theory' in mid-1970's. Rosch proposed that to classify objects, one can match them against a "prototype" i.e. an ideal example which exhibits the most representative features of the category of objects. This evolved the concept of frame based languages that used the prototype theory in the field of knowledge representation languages. Here, frames were used to represent knowledge like typical values, default values, or exceptions.
* The concept of prototypes was later picked up in programming languages in the 1980s when Borning proposed the description of a classless language. The underlying feature of this language was that new objects were essentially being produced by copying and modifying prototypes. The classless model of object oriented programming thus brought forward several issues related to class based programming and proposed various solutions based on the use of prototypes. [1]
* The concept of prototypes was later picked up in programming languages in the 1980s when Borning proposed the description of a classless language. The underlying feature of this language was that new objects were essentially being produced by copying and modifying prototypes. The classless model of object oriented programming thus brought forward several issues related to class based programming and proposed various solutions based on the use of prototypes. [1][7]


==Characteristics==
==Characteristics==
* Provide simpler description of objects. Use of concrete examples rather than abstract descriptions is preferred, unlike class based languages where abstractions (classes) are created to concrete objects (instances)
In prototype based languages, prototype is chosen by using concrete examples rather than abstracting out common attributes. This offers a programming model with fewer primitives. This is also a less restrictive knowledge representation model wherein objects are not coupled too tightly. Most popular object-oriented programming languages used are class based where all objects of a certain class share the same properties. At first the prototype paradigm is difficult to comprehend compared to class-based, such as Java and C++, which base their structure on the concept of two marked entities: classes and instances. We comparatively discuss the features of prototype based languages with class-based ones to understand its programming model and advantages.
* Offer a simpler programming model with fewer concepts and primitives. The traditional abstract data-type model have classes as the source of complexity because they play too many roles.
* Offer new capabilities to represent knowledge. Unlike classes who constrain objects too tightly. Eg, classes require every individual instance to have same behavior.
* Prototypical instances and cloning is a simpler programming model. A single class plays many roles (instance descriptors, method libraries, support for encapsulation, sharing, reuse, archictecture of programs).  
* Prototypes offer new capabilities to represent knowledge that are difficult to grasp in class-based languages, ie. different objects of same family with different structures and behaviours, exceptional objectrs, objects with viewpoints and hsaring at the object level, incomplete objects that can be classified.
* Real world - objects - classes which can be viewed as sets or prototypes
e.g. First view of sets name of class Car refers to SET of all cars and each car is member/instance of class
Second view name of class refers to typical car or concept of car that has all properties that all cars have in common


<p style="font-size:13px">  <b>Comparison between prototype-based languages and class-based languages</b> </p>
'''Comparison between prototype-based languages and class-based languages'''
{| class="wikitable" border="1" style="width: 900px; margin-left:60px;"
{| class="wikitable" border="1" style="width: 900px; margin-left:60px;"
|- style="text-align: center; "
|- style="text-align: center; "
! Class-Based (Java)
! Feature
! Prototype-Based (JavaScript)
! Class Based Programming e.g. Java, C#
! Prototype-Based Programming e.g. JavaScript, Self
|-
|-
| Class and instance are distinct entities.
| Object Model
| All objects are instances.
| Based on the class and instance entity model i.e. structure of object is defined by classes.
| Every object is an instance, there are no classes.
|-
|-
| Define a class with a class definition; instantiate a class with constructor methods.
| Object definition and creation
| Define and create a set of objects with constructor functions.
| Class defined with explicit class definition; class instantiated with help of constructors.
| Creates objects by assigning an object as the prototype where each prototype is associated with a constructor function.
|-
|-
| Abstract definitions are used.
| Abstraction
| No abstract definitions are present.
| Uses abstract definitions/representation.
| Does not use abstract definitions.
|-
|-
| Cannot change parent of a object.
| Parental Dependency
| Parent of object can be changed during runtime.
| The parent of an object cannot be altered
| Allows to change parent of object at runtime
|-
|-
| Construct an object hierarchy by using class definitions to define subclasses of existing classes.
| Inheritance
| Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
| Class definitions are used to define subclasses and the subclasses inherit properties by following the class chain.
| Objects inherit properties based on the hierarchy of the prototype chain.
|-
|-
| Inherit properties by following the class chain.
| Dynamic Structure
| Inherit properties by following the prototype chain.
| The class structure is static and contains all the properties that an instances of a class can have. One cannot add properties dynamically at run time.
|-
| The prototype or constructor function specifies the initial set of properties and one can add or remove properties dynamically of the particular object or of the entire set of objects.
| Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.
| Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
|-
|-
|}
|}


==Classification==
Thus, prototype based languages offer capabilities to represent knowledge in a way different than class based languages. Some of these representations are often difficult to represent in class based languages. Following are some examples:


There are several variations observed in these languages. They can be distinguished based on following traits.
# One can have different objects of the same family but having different structures and behaviors
# Objects with totally exceptional behavior
# Objects with view points and sharing at the object level
# Incomplete state objects


* '''Slots or methods and variables''': Some languages differentiate between methods and variables, while others treat them in the same way. ''Self '' treats methods and variables as same, which allows to over-ride an attribute with a method and vice versa.
Also, in the real world, entities or objects can be viewed as sets or prototypes. Sometimes modeling these architectural features in class-based languages exhibits certain limitations as they are rigid in terms of defining concepts with the idea of shared properties. Some real world examples where prototype based approach is preferred to class based one are traffic jam representation systems, greenhouse effect representation systems. [2]


* '''Inheritance and Sharing''': Clones in some languages don't get affected by change in their parent's behavior, thus help an object to not unexpectedly change through its clone. But languages that support delegation give two alternatives to create new objects, by cloning or by extension.
==Classification of Prototype Based Languages==
#'''Property Sharing''': It is the ability of an object to share all or some of its properties with another object. Extension creates a lifetime sharing.
#'''Value Sharing''': It is the ability of an object to share the values of a parent when an object is made using clone.


* '''Primitives of virtual machine''': The semantics of the  virtual machine primitives underlying each language distinguishes them.
It is very challenging to classify the set of prototype based languages due to the variations in implementation models for each language. However, these are needed at some level to adjudge which programming language model best suits the given needs. We classify these based on their ''primitive semantics'':
* '''Group-oriented constructions''': Classifies according to level of abstractness of these constructions.
 
#Purely prototype based: Self, Kevo, Taivalsaari, Agora, Garnetk **Moostrap, Omega, Obliq, NewtonScript
===Slots or methods and variables===
#Not Strictly prototype based: Object-Lisp, Yafool
A property is a binding of a name to a value within an object and each object is defined by a set of properties. Properties can be of two kinds: attributes or methods. In general programming terminology one can represent these properties of objects in two ways:
# Languages mixing prototypes and classes.
1. By separating attributes and methods .
2. By amalgamating attributes and methods into something known as "slots".
 
Thus, slots hold data values as well as methods. Some languages differentiate between methods and variables, while others treat them in the same way. [http://en.wikipedia.org/wiki/Self_%28programming_language%29 ''Self''] treats methods and variables as same, which allows to over-ride an attribute with a method and vice versa. In prototype based languages one can add or change not only data but also methods. For this reason, most prototype-based languages refer to both data and methods as "slots". Slots are defined to answer ''messages''. Either data or code can be found in a slot as the result of sending a message. Data is just returned, and code is actually executed. If a prototype does not contain a requested slot or does not know how to answer a specific message it may delegate the request to another prototype through an inheritance relation which is discussed next. [8]
 
 
<center>
[[Image:classification_ms.jpg]]
</center>
 
===Object Creation===
Objects can be created in two ways:
<br/>1. Ex nihilo (from scratch)
<br/>The systems using this model provide a special syntax for specifying the properties and behaviors of the newly created objects. These do not reference the existing objects for object creation. To implement this most programming languages use the ''Object'' prototype which contains all the common attributes and behaviors. It acts like a master blueprint for all other objects.
<br/>2. From existing object (by cloning or extending)
<br/>In this approach the new object then carries all the qualities of the original. Some languages enforce child object to maintain an explicit link to its prototype and changes in the prototype cause corresponding changes to be reflected in its clone. Other systems enforce that changes in cloned objects do not automatically propagate across descendants.
 
===Inheritance and Sharing===
Since the prototype is used to create other objects using cloning, its properties can be read through all objects of the class. These properties are actually a single shared copy. Thus, a read on these properties will retrieve the shared value from the prototype object. The cloned object can then set the value of one of these properties. This action will actually create a new property for that object. This new property can then 'shadow' or 'hide' the property from prototype object. Clones in some languages don't get affected by change in their parent's behavior, thus help an object to not unexpectedly change through its clone.
Languages are classified on the basis of how the primitives of writing on shared property, creating new property, message passing affect the prototypes.
e.g. Javascript and Kevo both handle object sharing differently [3].
 
===Delegation===
Delegation is a language feature that ‘delegates’ or ‘hands over’ a task to another object based on certain method lookups in the hierarchy at runtime. Thus, an object can use another object's behavior. This sounds a lot like inheritance, but inheritance allows the similar method dispatching based on the ‘type’ of object at compile time as opposed to delegation which works on instances. Thus, delegation can be used to support inheritance of methods in a prototype based system. 
 
Delegation is of two types:
<br/>1. Value Sharing: A type of sharing between representation of different entities. It is the ability of an object to share the values of a parent when an object is made using clone.
<br/>2. Property Sharing: A type of sharing between viewpoints on the same entity. It is the ability of an object to share all or some of its properties with another object.
 
===Concatenation===
Concatenation based prototype inheritance or concatenative-prototyping is another style to achieve inheritance. Instead of using traditional inheritance and delegation methods it uses incremental modification i.e. it allows duplicating existing objects and also flexibly editing them. This involves 2 operations 'new' and 'clone'
e.g. For creation of an object ColorWindow, the object creation would involve copying the existing 'Window' object and then adding new properties to the created copy using another module function say 'add'. Concatenation is achieved by late binding i.e. inherited properties that are defined earlier can be modified in an incremental fashion at run-time. There are also no links from the object to the prototype from which it is cloned. The advantage of this is that there are no side-effects of modifications on an object across other clones from the parent. The drawback is that if one needs to propagate these changes it involves more overhead. Besides, there is also memory wastage as there is no shared implementation. To avoid the issue of memory an additional field that recognizes if a parent is cloneable or not can be introduced. An example of a prototype language that uses concatenation is Kevo. [9]
 
'''Concatenation Vs Delegation'''
 
<div >
<div style="float:left;margin-left=15%">
[[Image:Delegation.jpg]]</div>
<div style="margin-left=15%">
<table border="1px" style="border-style:solid; border-width:thin; border-width:1px;">
<tr> <td> </td>
<td> Concatenation </td>
<td> Delegation</td>
</tr>
<tr>
  <td>read Car.model</td>
    <td>Mitsubishi</td>
      <td>Mitsubishi</td>
</tr>
<tr>
  <td>read Car.maxSpeed</td>
    <td>110</td>
      <td>110</td>
</tr>
<tr>
  <td>read Car.licencePlate</td>
    <td>NC765</td>
      <td>NC765</td>
</tr>
<tr>
  <td colspan="3" align="center">write Car.maxSpeed = 75</td>
  </tr>
<tr>
  <td>read Vehicle.maxSpeed</td>
    <td>75</td>
      <td>50</td>
</tr>
<tr>
  <td>read Truck.maxSpeed</td>
    <td>90</td>
      <td>90</td>
</tr>
<tr>
  <td>read Truck.model</td>
    <td>4 Wheel Drive</td>
      <td>4 Wheel Drive</td>
</tr>
<tr>
  <td>read Truck.licencePlate</td>
    <td>NCXXX</td>
      <td>NCXXX</td>
</tr>
<tr>
  <td colspan="3" align="center">write Truck.model = Volvo</td>
  </tr>
<tr>
  <td>read Truck.model</td>
  <td>Volvo</td>
  <td>Volvo</td>
</tr>
</table>
</div>
 
 
===Primitives of virtual machine===
The semantics of the  virtual machine primitives underlying each language also distinguishes the various types of programming languages.
 
Another parallel and overlapping classification of prototype based languages is based on group oriented constructions i.e. classification according to the level of abstractness of the constructions. Following are the high level groups:
<br/>1. Purely prototype based: Self, Kevo, Taivalsaari, [http://en.wikipedia.org/wiki/Agora_%28programming_language%29 Agora], Omega, [http://en.wikipedia.org/wiki/Obliq Obliq], [http://en.wikipedia.org/wiki/NewtonScript NewtonScript]
<br/>2. Not Strictly prototype based: [http://en.wikipedia.org/wiki/Object_Lisp Object-Lisp], Yafool
<br/>3. Languages mixing prototypes and classes.
 
==Programming Constructs==
Prototype based languages are varied in terms of their implementation patterns. We will consider the features of [http://en.wikipedia.org/wiki/JavaScript JavaScript], one of the most popular prototype based languages, for deeper insight into the typical implementation of programming constructs in prototyping.


==JavaScript - A Prototype Based Language==
===Creating Objects===
===Creating Objects===
Objects are defined as set of properties. A property is a binding within a object of a name to a value. Properties are of two kinds: attributes or methods. There are two ways represent properties of objects: either to separate attributes and methods or to amalgamate then into slots.
As mentioned earlier the object property can be either methods or attributes. While creating a new object the constructor function is used which typically wraps the initial values to properties of the object.
Objects can be created in two ways: 1. Ex nihilo (from scratch) 2. From existing object (by cloning or extending)
e.g.
A custom object is frequently defined by a constructor function, which typically parcels out initial values to properties of the object, as in the following example:
   function vehicle(model, licencePlate, maxSpeed) {
   Function car(plate, model, color) {
    this.plate = plate
     this.model = model
     this.model = model
     this.color = color
     this.licencePlate = licencePlate
    this.maxSpeed = maxSpeed
   }
   }
   var car1 = new car("AB 123", "Ford", "blue")
   var car1 = new car("Mitsubishi", "NC765", "135") ==> Javascript makes use of the new keyword.
   
   
After the precedint statements run, the car1 object has the following properites:
On creation the new object will have the properties:  
   car1.plate //value="AB 123"
   car1.model        // value="Mitsubishi
   car1.model    //value="Ford"
   car1.licencePlate // value="NC765"
   car1.color //value="blue"
   car1.maxSpeed    // value="135"
In prototype based languages one can add own customized properties to any object[10]. For this no special declarations are needed, just choosing the name of property and accessing it takes care of the inclusion of the property. We can illustrate this using the above example. Consider we add a new property to the constructor's prototype property like shown below-
 
  car.prototype.companyOwned = true


If you then add a new property to the constructor's prototype property, as in
This will then affect any new object that we are about to create as it automatically inherits the new property and its value. However, one can still override the value of the companyOwned property for an individual car object.
  car.prototype.companyOwned = true,
There are different variations to this rule and different programming languages can restrict this kind of change propagation.
any car object you already created or are about to create automatically inherits the new companyOwned property and its value. You can still override the value of the companyOwned property for an individual car object.


=====Cloning=====
=====Cloning=====
JavaScript supports Shallow Cloning and Deep Cloning.
There are 2 levels at which an object can be cloned. These are [http://en.wikipedia.org/wiki/Object_copy ''deep cloning''] and [http://en.wikipedia.org/wiki/Object_copy ''shallow cloning'']. In shallow cloning, a copy of an object is created wherein just the references of the sub-objects are copied. In deep cloning, a complete duplicate of the original is created, i.e. it creates not only the primitive values of the original object but also copies all its sub objects as well.
Shallow Cloning: Shallow cloning is a bitwise copy of an object. New object is created which is an exact copy that of the original one.  In case any objects are referring the fields of these objects, just the references are copied.
 
JavaScript supports shallow cloning. The copy(), clone() functions are used to clone an object.  
Deep Cloning: In deep cloning, complete duplicate copy of the original copy is created. Deep cloning creates not only the primitive values of the original objects but also copies all its sub objects as well.


The copy(), clone() and deepCopy() functions are used to clone a object.
i) clone() uses JavaScript's built-in prototype mechanism to create a cheap, shallow copy of a single Object.
clone() uses JavaScript's built-in prototype mechanism to create a cheap, shallow copy of a single Object.
e.g.
john2 = owl.clone(john);
john2 = owl.clone(john);


copy() makes a shallow, non-recursive copy of a single object.
ii) copy() makes a shallow, non-recursive copy of a single object.
e.g.
john4 = owl.copy(john);


john4 = owl.deepCopy(john);
One can define a deep copy algorithm to reursively copy every member explicitly.
deepCopy() is the entry point for the deep copy algorithm. Every member is recursively deep copied:


===Delegation===
===Delegation===
Delegation is a language feature that ‘delegates’ or ‘hands over’ a task to another object based on certain method lookups in the hierarchy at runtime. Thus, an object can use another object's behavior. This smells a lot like inheritance which allows the similar method dispatching based on the ‘type’ of object at compile time as opposed to delegation which works on instances.
However, it has been proposed that [refer pg 55 book] delegation be used to support inheritance of methods in a prototype based system.  Delegation can also be used for a number of advanced programming applications.
e.g. Dribble Stream [http://cs-people.bu.edu/yarom/research/oo/index.html]
Difference between inheritance and delegation also in above link
Instead of adhering to class, subclass and inheritance schemes of oo languages like java, javascript has prototype inheritance. Suppose your script wants to read or write a property of an object then following sequence search is performed over the property name:
# prototype property of instance is picked if defined
# if no local value check value of prototype property in object’s constructor
# continue protoype chain till match found upto native Object object.
e.g. http://robertnyman.com/2008/05/04/event-delegation-with-javascript/ Event delegation with javascript


Can give a diagram here
Instead of adhering to class, subclass and inheritance schemes, similar to object oriented languages, JavaScript has prototype inheritance. Suppose the script wants to read or write a property of an object then a search with the following sequence is performed over the property name:
# Prototype property of instance is picked if defined
# If no local value exists then check value of prototype property in object’s constructor
# Continue prototype chain till a match is found of the native ''Object'' object.


===Concatenation===
The best example of delegation would be event delegation in JavaScript. Events are the main components of JavaScript. They are triggers to invoke the script. Event delegation works on the principle assumption that if an event is triggered on an element then the same event is triggered on all of the element's ancestors in the tree. Delegation is achieved by attaching a handler to the parent DOM [document object model] element. [4]
Under pure prototyping, which is also referred to as concatenative prototypes, there are no visible pointers or links to the original prototype from which an object is cloned e.g Kevo.The prototype object is copied exactly, but given a different name (or reference). Behavior and attributes are simply duplicated as-is.
Advantages to this approach include the fact that object authors can alter the copy without worrying about side-effects across other children of the parent. A further advantage is that the computational cost of method lookup during dispatch is drastically reduced when compared to delegation, where an exhaustive search must be made of the entire delegation chain before failure to find a method or slot can be admitted.


Disadvantages to the concatenative approach include the organizational difficulty of propagating changes through the system; if a change occurs in a prototype, it is not immediately or automatically available on its clones. However, Kevo does provide additional primitives for publishing changes across sets of objects based on their similarity (so-called family resemblances) rather than through taxonomic origin, as is typical in the delegation model.
Consider the DOM model with a window containing a form and a button inside it. The onClick() event associated with the click trigger follows the order below to delegate responsibility:
Another disadvantage is that, in the most naive implementations of this model, additional memory is wasted (versus the delegation model) on each clone for the parts that have stayed the same between prototype and clone. However, it is possible to provide concatenative behavior to the programming while sharing implementation and data behind-the-scenes; such an approach is indeed followed by Kevo.[4]
<br/>1. Button.onClick()
<br/>2. Form.onClick()
<br/>3. Window.onClick()


An alternative quasi-solution to the problem of clones interfering with the behavior of the parent is to provide a means whereby the potential parent is flagged as being clonable or not. In MOO, this is achieved with the "f" flag. Only objects with the "f" flag can be cloned. In practice, this leads to certain objects serving as surrogate classes; their properties are kept constant to serve as initial values for their children. These children then tend to have the "f" flag not set.
The above propagation description is illustrated in the diagram below.
<center>
[[Image:formButton.jpg]]
</center>
This event propagation can be explicitly stopped using the function - event.stopPropagation(). The advantage achieved here is that a single event handler is used to manage a particular type of event for the entire page. This also consumes less memory. Thus event delegation is a great technique to avoid repetition of the same event assignments for elements within a parent element. This is particularly useful in the DOM model where elements are added dynamically to the page.


===Message Passing===
===Message Passing===
A message is a method call on an object. As different objects can have their own functions different functions, when invoking a function, it is necessary to make sure that the object implements that function. If a function is called on a object which does not invoke it, it throws an exception. But instead if we use message passing to invoke a function and if the object is not invoking that function, it simply returns a null.
One can use both function calls as well as message passing mechanism in JavaScript. The need to use message passing arises in complex JavaScript based user interfaces where one may have a single variable that refers to different kinds of objects. Each of these referenced objects can contain different functions. Thus, on every function call from the variable one has to make sure that it is calling a function that the target object implements. In such cases message passing is a more feasible solution wherein if a function is called and it is not implemented then no exception is thrown, instead a null is returned as an indication.


In JavaScript,
e.g.
  var myCar =  new Car();
  var newCar =  new Car();
  var returnValue = m(myCar, ‘carColor’, 1999);
  var returnValue = message(newCar, ‘carColor’, 1999);
(this code is created/modified)
A message will be passed to myCar object instance, which then invokes the function carColor that returns something.
The return value will be sent back and and will be assigned to returnValue just like a traditional function call. If the object doesn't implement carColor, it wont throw an exception, instead the return value will be just null.


(the “alternatively” below is copied entirely)
A message will be passed to newCar object instance, which then invokes the function carColor that ideally returns some color object.
Alternatively, an object can forward the message to another object, which might implement the requested function. All it has to do is to implement a function called forwardInvocation. It can even contain some logic like instantiating a globally accessible object which contains the requested function and then forward the message to it. Let's take for an example the following MooTools classes:
The return value will be sent back and and will be assigned to returnValue just like a traditional function call. If the object doesn't implement carColor, it wont throw an exception, instead the return value will be just null. Message passing can be extended to forward messages between objects. In JavaScript this is achieved when invoking object implements a function called forwardInvocation.


  var class1 = new Class({
e.g.
  var classOne = new Class({
     forwardInvocation: function(){
     forwardInvocation: function(){
         return object2;
         return objectTwo;
     }
     }
  });
  });


  var class2 = new Class({
  var classTwo = new Class({
     forwardInvocation: function(){
     forwardInvocation: function(){
         return object3;
         return objectThree;
     }
     }
  });
  });


  var class3 = new Class({
  var classThree= new Class({
     receivingFunction: function(){
     receivingFunction: function(){
         return 'Message received.'
         return 'New Message!'
     }
     }
  });
  });


  object1 = new class1();
  objectOne = new classOne();
  object2 = new class2();
  objectTwo = new classTwo();
  object3 = new class3();
  objectThree = new classThree();
 
alert(message(objectOne, 'receivingFunction')); ==> New Message!


Here, the message handler recursively forwards the message from objectOne to objectTwo until it finally reaches objectThree and the message is displayed as an alert message.
If we now run the following code:
alert(m(object1, 'receivingFunction'));
Then the message handler will recursively forward the message from object1 to object2 until it finally reaches object3, which then returns the string Message received that eventually will be displayed as an alert message (who would have guessed).


==Other Prototype Based Languages==
==Other Prototype Based Languages==


===Self===
===Self===
Self is similar to Smalltalk in syntax and semantics. but uses prototypes, unlike Smalltalk which uses class based paradigm.
Self is the canonical example of prototype based languages. It was developed by David Ungar and Randall Smith as part of the Klein project, which was a virtual machine written fully in Self. Self is similar to Smalltalk in syntax and semantics. It uses prototypes unlike Smalltalk which uses class based paradigm. Objects are comprised of slots where the slot stores name and reference to the object. Interaction with object is done with message sending. Slots are viewed as ''method slots'' and ''data slots''. Method slots are used to return result when a message is received, while data slots work like class variables in class based programming. New object is created by making a copy of existing object and then adding slots to get desired behavior. Data slots can be made as parent slots. A parent slot delegates message to the objects it refers, if the selector of that message is not matched to any slots in it. Thus, a method has to be written only once. It uses the ''trait'' object such that when methods are written in a ''trait'' object, it can be used by any other object.
 
'''Objects''': Objects are comprised of slots, the slot stores name and reference to the object. A slot contains the behavior and state of an object. Interaction with object is done with message sending. Slots can be categorized as ''method slots'' and ''data slots''. Method slots are used to return result when a message is received, while data slots work like class variables in class based programming.
 
'''Creation of Objects''': New object is created by making a copy of existing object and then adding slots to get desired behavior.


'''Inheritance''': Data slots can be made as parent slots. A parent slot delegates message to the objects it refers, if the selector of that message is not matched to any slots in it. Thus, a method has to be written only once. When methods are written in a ''triat'' object, it can be used by any other object.
===Omega===
Omega is a prototype based language developed by Günther Blaschek. It is a statically typed language. It uses inheritance instead of delegation by introducing types where every prototype corresponds to a type. Thus a subtype hierarchy is defined by using inheritance between prototypes. Omega characterizes into a prototype based language because prototypes can be replicated by cloning and altered by making modifications prior to its instance formation. Other key features of Omega are :
<br/>
* Single inheritance
* Conditional assignments
* Genericity i.e. providing parametrized types. E.g. List (of:Float) or List (of:Student).   
* Garbage collection
* Monomorphic types i.e. one cannot perform overloading without providing a specific type signature. The functions are thus restrictive as they work on only one type.


===Kevo===
===Kevo===
Kevo is another prototype based programming language created by Antero Taivalsaari for Macintosh computers. It is semantically similar to the languages Self and Omega and resembles Forth syntactically. It varies from other prototype based languages in the way inheritance and delegation are handled in it. This is mainly because Kevo objects are self-contained and do not share properties with other objects i.e. it follows the concatenation model where changes in the prototype do not propagate to the cloned object. Kevo provides the extensibility to manipulate objects flexibly by use of certain module operations. These module operations are capable of publishing updates from the prototype across a certain set of objects based on their similarity in the family tree by use of some additional primitives. Another distinct feature of Kevo is that it uses a threaded code interpreter.


===NewtonScript===
===NewtonScript===
NewtonScript was created by Walter Smith for Apple's Newton MessagePad. The motivation for creation of this language was designing GUI for the Newton platform with low memory consumption. As this is an issue in class-based languages wherein an instantiation of a class causes memory being allocated for all object attributes, Walter chose to design a prototype based language wherein creating an instance would be equivalent to creating a frame that inherits from some prototype frame. Note that this class creation scheme does not allow data hiding, instance variables are still accessible from other functions not belonging to the class. It allows factoring out common behavior of frames and gives some clearly defined interface to a set of data. Applications of NewtonScript are now only restricted to mainly the Newton platform mobile and embedded devices. Despite running on a platform with only very low RAM, NewtonScript supports many modern language features such as exceptions and garbage collection. [5]


==Disadvanatages/Criticism==
==Criticism==
 
* Although class based programming seems to be very restrictive in nature, it provides better type-safety and predictability. This is not the case with prototype based languages wherein this violation is particularly observed in case of the delegation mechanism which allows the parent to be modified during runtime. Any unintended changes will affect the parent and alter the behavior of system which might be undesirable.
* Unlike prototypes, classes provide a contractual guarantee to their objects and to their users to about their behavior. Concerns involving safety and predictability are better handled by classes. Example: Delegation allows an object to change its parent during runtime. If ill-planed changes are made using delegation, the program will behave unpredictable.
* Prototype based languages were developed incrementally based on specific platforms or implementation requirements. Thus, the larger community of developers is not well versed with its concepts. [11]
 
* Efficiency of language-compiler reduces when prototypes are used. These languages don't allow developing efficient methods and instance variable lookups.


* The community of software developers in present day is unfamiliar with the concept of prototypes and languages based on them.
==Applications==
Most of the prototype based languages were developed as needs to certain specific applications. These applications include:
<br/>1.  Low memory consumption based systems e.g. NewtonScript [6]
<br/>2.  Vocabulary acquisition and teaching analysis
<br/>3.  Mental lexicon analysis
<br/>4.  Cognitive linguistics and linguistic data analysis
<br/>5.  Traffic jam representation systems
<br/>6. Greenhouse effect representation systems [2]


==Conclusion==
==Conclusion==


Applications:
Thus prototype based languages propose a vision of object-oriented programming based on the notion of a prototype. Numerous prototype based languages have been designed and implemented. Most popular ones include Self, Kevo, Agora, Garnet, GlyphicScript, Moostrap, Omega, Obliq and NewtonScript. Some languages like Object-Lisp and Yafool which are not strictly prototyped but offer related mechanisms by use of prototyping at the implementation level have also been developed. [1] All of these represent another view of the real world objects not relying on advance categorization and classification, but rather on making the concepts in the problem domain as tangible and intuitive as possible. [8]
The prototype theory  has been particularly fruitful in providing several researchers with a convenient explanation of some phenomena in studies of vocabulary acquisition and teaching, mental lexicon, as well as in studies of cognitive linguistics and linguistic data.
[http://www.directessays.com/viewpaper/78763.html]
 
==Suggested Reading/See Also==
External Links
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.123.9056&rep=rep1&type=pdf
Internal Links
 
==References==
* Borning A (1986), ''Classes versus Prototypes in Object-Oriented Languages'', IEEE Computer Society Press, [http://portal.acm.org/citation.cfm?id=324538 In Proceedings of the IEEE/ACM Fall Joint Conference].
 
* please put all the book references here..  


* please put all the book references here..  
==Suggested Reading==
# [http://en.wikipedia.org/wiki/Prototype_pattern Prototype Design Pattern]
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.123.9056&rep=rep1&type=pdf Prototype Thoery, Cognitive Linguistics and Pedagogical Grammar - R.K Johnson]
# [http://delivery.acm.org/10.1145/200000/191101/p102-smith.pdf?key1=191101&key2=2362067821&coll=GUIDE&dl=GUIDE&CFID=106656954&CFTOKEN=21383009 Prototype-Based Languages: Object Lessons from Class-Free Programming - Mark Lentczner, Walter R., Smith Antero lbivalsaari, David Ungar]


* please put all the book references here..
==References / External Links==


* Marcus Arnstrom, Mikael Christiansen, Daniel Sehlberg  ''Prototype-based programming'' (May 2003).
# Marcus Arnstrom, Mikael Christiansen, Daniel Sehlberg (May 2003), ''Prototype-based programming''.
# Borning A (1986), ''Classes versus Prototypes in Object-Oriented Languages'', IEEE Computer Society Press, [http://portal.acm.org/citation.cfm?id=324538 In Proceedings of the IEEE/ACM Fall Joint Conference].
# [https://developer.mozilla.org/en/JavaScript/Guide/Details_of_the_Object_Model Prototype and Class based programming languages]
# [http://docstore.mik.ua/orelly/web/jscript/ch07_04.html Concept of Object Prototypes]
# [http://www.quirksmode.org/js/introevents.html Event Delegation with JavaScript]
# [http://www.grin.com/e-book/96313/the-newton-script-programming-language The NewtonScript Programming Language]
# [http://www.directessays.com/viewpaper/78763.html Prototype Theory]
# James Noble, Antero Taivalsaari, Ivan Moore, ''Prototype Based Programming - Concepts, Languages and Applications''
# C. Dony, J. Malenfant, D. Bardon, [http://www.lirmm.fr/~dony/postscript/proto-book.pdf ''Classifying Prototype Based Languages'']
# [http://www.learn-javascript-tutorial.com/Prototype-Based-Inheritance.cfm Prototype-Based Inheritance]
# [http://en.wikipedia.org/wiki/Prototype-based_programming Criticism of prototype based programming languages]

Latest revision as of 03:18, 30 October 2010

Prototype Based Programming

"Objects in the real world have only one thing in common: they are all different" (anonymous, A. Taivalsaari, JOOP, Nov. 1997)

Introduction

Prototype based programming is an object oriented programming methodology. It differs from the other classes of object oriented languages due to its main characteristic feature that no classes are present in the language constructs. Behavior reuse or inheritance is performed by cloning some instance or prototype objects. Thus, it is also known as 'instance-based programming' or 'class-less based programming' and such languages are known as 'prototype based languages'.

Objects used in prototype based programming are referred as prototypes, which resemble an instance of a class in class-based programming. It differs from a class instance as one can add or remove variables and methods at any level of a single object, without worrying if the object still fits in the system. Typically, new objects are created by copying existing objects, which is called as cloning.

Object Oriented programming languages are classified based on following criteria:

  • Class based : Object instances are created fro skeleton or blueprint of the class.
  • Prototype based : Object instances are created from concrete examples and other objects are created with such a prototype reference.
  • Automata based : The program is thought of as a model of a finite state machine or any other formal automata.
  • Based on separation of concerns e.g. aspect oriented languages

The figure below shows where prototype based languages fit in the broad classification of object oriented languages.

Since prototype based languages do not distinguish between classes and instances, there is the concept of just objects. There are three types of objects- normal objects, prototypes and traits. Prototypes and traits are not real objects but the term object is loosely used to signify their specialization feature. Normal objects are used to represent the local state. Prototypes are blueprints to generate clones. Traits, if used in the programming language, are abstract descriptions of objects that do not possess a state i.e. only provides a set of methods. Traits are never cloned or used directly and are intended only to be used as the shared parents of normal objects. [1]

History

  • Eleanor Rosch first introduced the 'Prototype Theory' in mid-1970's. Rosch proposed that to classify objects, one can match them against a "prototype" i.e. an ideal example which exhibits the most representative features of the category of objects. This evolved the concept of frame based languages that used the prototype theory in the field of knowledge representation languages. Here, frames were used to represent knowledge like typical values, default values, or exceptions.
  • The concept of prototypes was later picked up in programming languages in the 1980s when Borning proposed the description of a classless language. The underlying feature of this language was that new objects were essentially being produced by copying and modifying prototypes. The classless model of object oriented programming thus brought forward several issues related to class based programming and proposed various solutions based on the use of prototypes. [1][7]

Characteristics

In prototype based languages, prototype is chosen by using concrete examples rather than abstracting out common attributes. This offers a programming model with fewer primitives. This is also a less restrictive knowledge representation model wherein objects are not coupled too tightly. Most popular object-oriented programming languages used are class based where all objects of a certain class share the same properties. At first the prototype paradigm is difficult to comprehend compared to class-based, such as Java and C++, which base their structure on the concept of two marked entities: classes and instances. We comparatively discuss the features of prototype based languages with class-based ones to understand its programming model and advantages.

Comparison between prototype-based languages and class-based languages

Feature Class Based Programming e.g. Java, C# Prototype-Based Programming e.g. JavaScript, Self
Object Model Based on the class and instance entity model i.e. structure of object is defined by classes. Every object is an instance, there are no classes.
Object definition and creation Class defined with explicit class definition; class instantiated with help of constructors. Creates objects by assigning an object as the prototype where each prototype is associated with a constructor function.
Abstraction Uses abstract definitions/representation. Does not use abstract definitions.
Parental Dependency The parent of an object cannot be altered Allows to change parent of object at runtime
Inheritance Class definitions are used to define subclasses and the subclasses inherit properties by following the class chain. Objects inherit properties based on the hierarchy of the prototype chain.
Dynamic Structure The class structure is static and contains all the properties that an instances of a class can have. One cannot add properties dynamically at run time. The prototype or constructor function specifies the initial set of properties and one can add or remove properties dynamically of the particular object or of the entire set of objects.

Thus, prototype based languages offer capabilities to represent knowledge in a way different than class based languages. Some of these representations are often difficult to represent in class based languages. Following are some examples:

  1. One can have different objects of the same family but having different structures and behaviors
  2. Objects with totally exceptional behavior
  3. Objects with view points and sharing at the object level
  4. Incomplete state objects

Also, in the real world, entities or objects can be viewed as sets or prototypes. Sometimes modeling these architectural features in class-based languages exhibits certain limitations as they are rigid in terms of defining concepts with the idea of shared properties. Some real world examples where prototype based approach is preferred to class based one are traffic jam representation systems, greenhouse effect representation systems. [2]

Classification of Prototype Based Languages

It is very challenging to classify the set of prototype based languages due to the variations in implementation models for each language. However, these are needed at some level to adjudge which programming language model best suits the given needs. We classify these based on their primitive semantics:

Slots or methods and variables

A property is a binding of a name to a value within an object and each object is defined by a set of properties. Properties can be of two kinds: attributes or methods. In general programming terminology one can represent these properties of objects in two ways: 1. By separating attributes and methods . 2. By amalgamating attributes and methods into something known as "slots".

Thus, slots hold data values as well as methods. Some languages differentiate between methods and variables, while others treat them in the same way. Self treats methods and variables as same, which allows to over-ride an attribute with a method and vice versa. In prototype based languages one can add or change not only data but also methods. For this reason, most prototype-based languages refer to both data and methods as "slots". Slots are defined to answer messages. Either data or code can be found in a slot as the result of sending a message. Data is just returned, and code is actually executed. If a prototype does not contain a requested slot or does not know how to answer a specific message it may delegate the request to another prototype through an inheritance relation which is discussed next. [8]


Object Creation

Objects can be created in two ways:
1. Ex nihilo (from scratch)
The systems using this model provide a special syntax for specifying the properties and behaviors of the newly created objects. These do not reference the existing objects for object creation. To implement this most programming languages use the Object prototype which contains all the common attributes and behaviors. It acts like a master blueprint for all other objects.
2. From existing object (by cloning or extending)
In this approach the new object then carries all the qualities of the original. Some languages enforce child object to maintain an explicit link to its prototype and changes in the prototype cause corresponding changes to be reflected in its clone. Other systems enforce that changes in cloned objects do not automatically propagate across descendants.

Inheritance and Sharing

Since the prototype is used to create other objects using cloning, its properties can be read through all objects of the class. These properties are actually a single shared copy. Thus, a read on these properties will retrieve the shared value from the prototype object. The cloned object can then set the value of one of these properties. This action will actually create a new property for that object. This new property can then 'shadow' or 'hide' the property from prototype object. Clones in some languages don't get affected by change in their parent's behavior, thus help an object to not unexpectedly change through its clone. Languages are classified on the basis of how the primitives of writing on shared property, creating new property, message passing affect the prototypes. e.g. Javascript and Kevo both handle object sharing differently [3].

Delegation

Delegation is a language feature that ‘delegates’ or ‘hands over’ a task to another object based on certain method lookups in the hierarchy at runtime. Thus, an object can use another object's behavior. This sounds a lot like inheritance, but inheritance allows the similar method dispatching based on the ‘type’ of object at compile time as opposed to delegation which works on instances. Thus, delegation can be used to support inheritance of methods in a prototype based system.

Delegation is of two types:
1. Value Sharing: A type of sharing between representation of different entities. It is the ability of an object to share the values of a parent when an object is made using clone.
2. Property Sharing: A type of sharing between viewpoints on the same entity. It is the ability of an object to share all or some of its properties with another object.

Concatenation

Concatenation based prototype inheritance or concatenative-prototyping is another style to achieve inheritance. Instead of using traditional inheritance and delegation methods it uses incremental modification i.e. it allows duplicating existing objects and also flexibly editing them. This involves 2 operations 'new' and 'clone' e.g. For creation of an object ColorWindow, the object creation would involve copying the existing 'Window' object and then adding new properties to the created copy using another module function say 'add'. Concatenation is achieved by late binding i.e. inherited properties that are defined earlier can be modified in an incremental fashion at run-time. There are also no links from the object to the prototype from which it is cloned. The advantage of this is that there are no side-effects of modifications on an object across other clones from the parent. The drawback is that if one needs to propagate these changes it involves more overhead. Besides, there is also memory wastage as there is no shared implementation. To avoid the issue of memory an additional field that recognizes if a parent is cloneable or not can be introduced. An example of a prototype language that uses concatenation is Kevo. [9]

Concatenation Vs Delegation

Concatenation Delegation
read Car.model Mitsubishi Mitsubishi
read Car.maxSpeed 110 110
read Car.licencePlate NC765 NC765
write Car.maxSpeed = 75
read Vehicle.maxSpeed 75 50
read Truck.maxSpeed 90 90
read Truck.model 4 Wheel Drive 4 Wheel Drive
read Truck.licencePlate NCXXX NCXXX
write Truck.model = Volvo
read Truck.model Volvo Volvo


Primitives of virtual machine

The semantics of the virtual machine primitives underlying each language also distinguishes the various types of programming languages.

Another parallel and overlapping classification of prototype based languages is based on group oriented constructions i.e. classification according to the level of abstractness of the constructions. Following are the high level groups:
1. Purely prototype based: Self, Kevo, Taivalsaari, Agora, Omega, Obliq, NewtonScript
2. Not Strictly prototype based: Object-Lisp, Yafool
3. Languages mixing prototypes and classes.

Programming Constructs

Prototype based languages are varied in terms of their implementation patterns. We will consider the features of JavaScript, one of the most popular prototype based languages, for deeper insight into the typical implementation of programming constructs in prototyping.

Creating Objects

As mentioned earlier the object property can be either methods or attributes. While creating a new object the constructor function is used which typically wraps the initial values to properties of the object. e.g.

 function vehicle(model, licencePlate, maxSpeed) {
   this.model = model
   this.licencePlate = licencePlate
   this.maxSpeed = maxSpeed
 }
 var car1 = new car("Mitsubishi", "NC765", "135") ==> Javascript makes use of the new keyword.

On creation the new object will have the properties:

 car1.model        // value="Mitsubishi
 car1.licencePlate // value="NC765"
 car1.maxSpeed     // value="135"

In prototype based languages one can add own customized properties to any object[10]. For this no special declarations are needed, just choosing the name of property and accessing it takes care of the inclusion of the property. We can illustrate this using the above example. Consider we add a new property to the constructor's prototype property like shown below-

 car.prototype.companyOwned = true

This will then affect any new object that we are about to create as it automatically inherits the new property and its value. However, one can still override the value of the companyOwned property for an individual car object. There are different variations to this rule and different programming languages can restrict this kind of change propagation.

Cloning

There are 2 levels at which an object can be cloned. These are deep cloning and shallow cloning. In shallow cloning, a copy of an object is created wherein just the references of the sub-objects are copied. In deep cloning, a complete duplicate of the original is created, i.e. it creates not only the primitive values of the original object but also copies all its sub objects as well.

JavaScript supports shallow cloning. The copy(), clone() functions are used to clone an object.

i) clone() uses JavaScript's built-in prototype mechanism to create a cheap, shallow copy of a single Object.

e.g.
john2 = owl.clone(john);

ii) copy() makes a shallow, non-recursive copy of a single object.

e.g.
john4 = owl.copy(john);

One can define a deep copy algorithm to reursively copy every member explicitly.

Delegation

Instead of adhering to class, subclass and inheritance schemes, similar to object oriented languages, JavaScript has prototype inheritance. Suppose the script wants to read or write a property of an object then a search with the following sequence is performed over the property name:

  1. Prototype property of instance is picked if defined
  2. If no local value exists then check value of prototype property in object’s constructor
  3. Continue prototype chain till a match is found of the native Object object.

The best example of delegation would be event delegation in JavaScript. Events are the main components of JavaScript. They are triggers to invoke the script. Event delegation works on the principle assumption that if an event is triggered on an element then the same event is triggered on all of the element's ancestors in the tree. Delegation is achieved by attaching a handler to the parent DOM [document object model] element. [4]

Consider the DOM model with a window containing a form and a button inside it. The onClick() event associated with the click trigger follows the order below to delegate responsibility:
1. Button.onClick()
2. Form.onClick()
3. Window.onClick()

The above propagation description is illustrated in the diagram below.

This event propagation can be explicitly stopped using the function - event.stopPropagation(). The advantage achieved here is that a single event handler is used to manage a particular type of event for the entire page. This also consumes less memory. Thus event delegation is a great technique to avoid repetition of the same event assignments for elements within a parent element. This is particularly useful in the DOM model where elements are added dynamically to the page.

Message Passing

One can use both function calls as well as message passing mechanism in JavaScript. The need to use message passing arises in complex JavaScript based user interfaces where one may have a single variable that refers to different kinds of objects. Each of these referenced objects can contain different functions. Thus, on every function call from the variable one has to make sure that it is calling a function that the target object implements. In such cases message passing is a more feasible solution wherein if a function is called and it is not implemented then no exception is thrown, instead a null is returned as an indication.

e.g.

var newCar =  new Car();
var returnValue = message(newCar, ‘carColor’, 1999);

A message will be passed to newCar object instance, which then invokes the function carColor that ideally returns some color object. The return value will be sent back and and will be assigned to returnValue just like a traditional function call. If the object doesn't implement carColor, it wont throw an exception, instead the return value will be just null. Message passing can be extended to forward messages between objects. In JavaScript this is achieved when invoking object implements a function called forwardInvocation.

e.g.

var classOne = new Class({
   forwardInvocation: function(){
       return objectTwo;
   }
});
var classTwo = new Class({
   forwardInvocation: function(){
       return objectThree;
   }
});
var classThree= new Class({
   receivingFunction: function(){
       return 'New Message!'
   }
});
objectOne = new classOne();
objectTwo = new classTwo();
objectThree = new classThree();
alert(message(objectOne, 'receivingFunction')); ==> New Message!

Here, the message handler recursively forwards the message from objectOne to objectTwo until it finally reaches objectThree and the message is displayed as an alert message.

Other Prototype Based Languages

Self

Self is the canonical example of prototype based languages. It was developed by David Ungar and Randall Smith as part of the Klein project, which was a virtual machine written fully in Self. Self is similar to Smalltalk in syntax and semantics. It uses prototypes unlike Smalltalk which uses class based paradigm. Objects are comprised of slots where the slot stores name and reference to the object. Interaction with object is done with message sending. Slots are viewed as method slots and data slots. Method slots are used to return result when a message is received, while data slots work like class variables in class based programming. New object is created by making a copy of existing object and then adding slots to get desired behavior. Data slots can be made as parent slots. A parent slot delegates message to the objects it refers, if the selector of that message is not matched to any slots in it. Thus, a method has to be written only once. It uses the trait object such that when methods are written in a trait object, it can be used by any other object.

Omega

Omega is a prototype based language developed by Günther Blaschek. It is a statically typed language. It uses inheritance instead of delegation by introducing types where every prototype corresponds to a type. Thus a subtype hierarchy is defined by using inheritance between prototypes. Omega characterizes into a prototype based language because prototypes can be replicated by cloning and altered by making modifications prior to its instance formation. Other key features of Omega are :

  • Single inheritance
  • Conditional assignments
  • Genericity i.e. providing parametrized types. E.g. List (of:Float) or List (of:Student).
  • Garbage collection
  • Monomorphic types i.e. one cannot perform overloading without providing a specific type signature. The functions are thus restrictive as they work on only one type.

Kevo

Kevo is another prototype based programming language created by Antero Taivalsaari for Macintosh computers. It is semantically similar to the languages Self and Omega and resembles Forth syntactically. It varies from other prototype based languages in the way inheritance and delegation are handled in it. This is mainly because Kevo objects are self-contained and do not share properties with other objects i.e. it follows the concatenation model where changes in the prototype do not propagate to the cloned object. Kevo provides the extensibility to manipulate objects flexibly by use of certain module operations. These module operations are capable of publishing updates from the prototype across a certain set of objects based on their similarity in the family tree by use of some additional primitives. Another distinct feature of Kevo is that it uses a threaded code interpreter.

NewtonScript

NewtonScript was created by Walter Smith for Apple's Newton MessagePad. The motivation for creation of this language was designing GUI for the Newton platform with low memory consumption. As this is an issue in class-based languages wherein an instantiation of a class causes memory being allocated for all object attributes, Walter chose to design a prototype based language wherein creating an instance would be equivalent to creating a frame that inherits from some prototype frame. Note that this class creation scheme does not allow data hiding, instance variables are still accessible from other functions not belonging to the class. It allows factoring out common behavior of frames and gives some clearly defined interface to a set of data. Applications of NewtonScript are now only restricted to mainly the Newton platform mobile and embedded devices. Despite running on a platform with only very low RAM, NewtonScript supports many modern language features such as exceptions and garbage collection. [5]

Criticism

  • Although class based programming seems to be very restrictive in nature, it provides better type-safety and predictability. This is not the case with prototype based languages wherein this violation is particularly observed in case of the delegation mechanism which allows the parent to be modified during runtime. Any unintended changes will affect the parent and alter the behavior of system which might be undesirable.
  • Prototype based languages were developed incrementally based on specific platforms or implementation requirements. Thus, the larger community of developers is not well versed with its concepts. [11]

Applications

Most of the prototype based languages were developed as needs to certain specific applications. These applications include:
1. Low memory consumption based systems e.g. NewtonScript [6]
2. Vocabulary acquisition and teaching analysis
3. Mental lexicon analysis
4. Cognitive linguistics and linguistic data analysis
5. Traffic jam representation systems
6. Greenhouse effect representation systems [2]

Conclusion

Thus prototype based languages propose a vision of object-oriented programming based on the notion of a prototype. Numerous prototype based languages have been designed and implemented. Most popular ones include Self, Kevo, Agora, Garnet, GlyphicScript, Moostrap, Omega, Obliq and NewtonScript. Some languages like Object-Lisp and Yafool which are not strictly prototyped but offer related mechanisms by use of prototyping at the implementation level have also been developed. [1] All of these represent another view of the real world objects not relying on advance categorization and classification, but rather on making the concepts in the problem domain as tangible and intuitive as possible. [8]

Suggested Reading

  1. Prototype Design Pattern
  2. Prototype Thoery, Cognitive Linguistics and Pedagogical Grammar - R.K Johnson
  3. Prototype-Based Languages: Object Lessons from Class-Free Programming - Mark Lentczner, Walter R., Smith Antero lbivalsaari, David Ungar

References / External Links

  1. Marcus Arnstrom, Mikael Christiansen, Daniel Sehlberg (May 2003), Prototype-based programming.
  2. Borning A (1986), Classes versus Prototypes in Object-Oriented Languages, IEEE Computer Society Press, In Proceedings of the IEEE/ACM Fall Joint Conference.
  3. Prototype and Class based programming languages
  4. Concept of Object Prototypes
  5. Event Delegation with JavaScript
  6. The NewtonScript Programming Language
  7. Prototype Theory
  8. James Noble, Antero Taivalsaari, Ivan Moore, Prototype Based Programming - Concepts, Languages and Applications
  9. C. Dony, J. Malenfant, D. Bardon, Classifying Prototype Based Languages
  10. Prototype-Based Inheritance
  11. Criticism of prototype based programming languages