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

From Expertiza_Wiki
Jump to navigation Jump to search
Line 179: Line 179:
* please put all the book references here..  
* please put all the book references here..  


* Marcus Arnstr¨om, Mikael Christiansen, Daniel Sehlberg (May 2003) ''Prototype-based programming''.
* Marcus Arnstr¨om, Mikael Christiansen, Daniel Sehlberg ''Prototype-based programming'' (May 2003).

Revision as of 04:10, 19 October 2010

Prototype Based Programming

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.

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 languages are known as prototype based languages.

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]

Why Prototype based solutions?

  • 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)
  • 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

Comparison between prototype-based languages and class-based languages

Class-Based (Java) Prototype-Based (JavaScript)
Class and instance are distinct entities. All objects are instances.
Define a class with a class definition; instantiate a class with constructor methods. Define and create a set of objects with constructor functions.
Create a single object with the new operator. Same.
Construct an object hierarchy by using class definitions to define subclasses of existing classes. Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inherit properties by following the class chain. Inherit properties by following the prototype chain.
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

Prototype based languages can be classified in following categories.

  • Primives of virtual maching underlying each language - Classifies language according to semantics of these primitves
  • Group-oriented constructions provided in language - Classifies acc to level of abstractness of these constructions.
  • Design and implementation:
    • Purely prototype based: Self, Kevo, Taivalsaari, Agora, Garnetk **Moostrap, Omega, Obliq, NewtonScript
    • Not Strictly prototype based: Object-Lisp, Yafool
    • Languages mixing prototypes and classes:

JavaScript - A Prototype Based Language

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. Objects can be created in two ways: 1. Ex nihilo (from scratch) 2. From existing object (by cloning or extending) 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 car(plate, model, color) {
   this.plate = plate
   this.model = model
   this.color = color
 }
 var car1 = new car("AB 123", "Ford", "blue")

After the precedint statements run, the car1 object has the following properites:

 car1.plate 	//value="AB 123"
 car1.model    //value="Ford"
 car1.color 	//value="blue"

If you then add a new property to the constructor's prototype property, as in

 car.prototype.companyOwned = true, 

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

JavaScript supports Shallow Cloning and Deep Cloning. 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.

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. clone() uses JavaScript's built-in prototype mechanism to create a cheap, shallow copy of a single Object. john2 = owl.clone(john);

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

john4 = owl.deepCopy(john); deepCopy() is the entry point for the deep copy algorithm. Every member is recursively deep copied:

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 [1] 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:

  1. prototype property of instance is picked if defined
  2. if no local value check value of prototype property in object’s constructor
  3. 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

Concatenation

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. 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]

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.

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.

In JavaScript,

var myCar =  new Car();
var returnValue = m(myCar, ‘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) 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:

var class1 = new Class({
   forwardInvocation: function(){
       return object2;
   }
});
var class2 = new Class({
   forwardInvocation: function(){
       return object3;
   }
});
var class3 = new Class({
   receivingFunction: function(){
       return 'Message received.'
   }
});
object1 = new class1();
object2 = new class2();
object3 = new class3();


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).

Disadvanatages/Criticism

  • 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.
  • 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.

Conclusion

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

  • please put all the book references here..
  • please put all the book references here..
  • please put all the book references here..
  • Marcus Arnstr¨om, Mikael Christiansen, Daniel Sehlberg Prototype-based programming (May 2003).