CSC/ECE 517 Fall 2010/ch6 6a RJ

From Expertiza_Wiki
Jump to navigation Jump to search

Survey of selected Delegation-based Programming Languages

Delegation-based programming languages, also known as Prototype-based programming languages, represent a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes [1]. This model can also be known as class-less, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming.

The original, and most canonical, example of a prototype-based language is the programming language Self developed by David Ungar and Randall Smith. Since the late 1990s, the classless programming style has grown increasingly popular, and has been adopted for the languages JavaScript, ActionScript, Cecil, NewtonScript, Io, Moo, REBOL,
Lisaac, Lua and several others.[2].

An earlier Wiki textbook chapter described the characteristics, classification, and programming constructs of delegation-based (i.e. prototype-based) programming languages. This topic will focus briefly on the features of three Delegation-based programming languages: Lua, JavaScript, and Io.

Lua

Lua is a powerful, fast, lightweight, embeddable scripting language. It combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping [3]]. Lua is a free open-source software product.

History of Lua

Lua was created in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes, members of the Computer Graphics Technology Group (Tecgraf) at the Pontifical Catholic University of Rio de Janeiro]in Brazil. [4] The design of the Lua programming language was influenced by the programming languages Scheme, SNOBAL, Modula-2,
CLU, and C++.

Lua and Object Oriented Programming

Lua isn't an object oriented languages in the sense that you define classes, create objects with a new method, define interfaces and declare variables to be private or protected. Lua is a tool in which you can use object oriented techniques with a freedom and flexibility that you don't have with a straitjacket language such as Java.[5]

Below is a look at some coding in Lua:

Initially, a couple of named pieces of code (functions) are defined which take a table as their parameter, and some functionality is provided within them that manipulates the table:

function effage(animule)
  return animule.age * animule.factor
  end
function stone(thecrows)
  return "as da hills"
  end

Then a number of tables are defined, each representing a single "something" [object] which contains attributes / properties / characteristic values (choose whatever you feel is the most appropriate word.) Significantly, we also add in to the table the function code, just defined above, which can operate on the other elements within that table. This can be done because functions in Lua are held in "first class variable" just like any other user supplied elements, and that an assignment copies a reference, so that we're not cloning hundreds of copies of what could be substantial code.

gypsy = {breed = "dog", age = 3, weight = 28,
  factor = 7, name = 'Gypsy Ellis', efa = effage}
rocky = {breed = "rock", weight = 28,
  type = "Granite", name = 'Rocky Bamboa', efa = stone}
charlie = {breed = "cat", age = 13, weight = 4,
  factor = 6, name = "Charlie Ellis", efa = effage}
flipper = {breed = "dolphin", age = 7, weight = 300,
  factor = 2, name = "Flipper Lichtenstein", efa = effage}

Although "structured" programmers might have chosen to have an array of breeds, an array of ages, etc, we have chosen to use a separate table for each of the disparate value types associated with an individual item - and we can now make up a table of each of those items - a table of tables, or an "array of objects" using OO terminology:

pets = {gypsy, charlie, rocky, flipper}

We can then loop through our array of objects, accessing individual member elements (attributes / properties) by name, and running pieces of code which are referenced from within each of them to perform actions on the data they hold ...so that those functions have now turned (in OO terms) into methods. With different methods referenced within differing objects, you'll see that we've implemented polymorphism via the back door!

for k,v in pairs(pets) do
  print (k,v,v.name)
  print ("yay",v.efa(v))
  end


JavaScript

JavaScript is a very flexible object-oriented language when it comes to syntax, and it is a language where there are no classes [6]. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages like C++ or Java.

History

JavaScript was originally developed by Brendan Eich of Netscape under the name Mocha, which was later renamed to LiveScript, and finally to JavaScript. [7] [8] LiveScript was the official name for the language when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but it was renamed JavaScript in a joint announcement with Sun Microsystems on December 4, 1995 [9] when it was deployed in the Netscape browser version 2.0B3. [10]

The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language.

JavaScript has become one of the most popular programming languages on the web. [11]

Objects in JavaScript

In JavaScript an object and its instance variables and methods can be created in a JavaScript function. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for a class created using function(), you use the this keyword, as seen in the following example:


function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

To instantiate an object of the Apple class, set some properties and call methods you can do the following:

var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

JavaScript functions can also be used to create a Singleton class as follows:

var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

Once the JavaScript object has been created using the Singleton class in the function, the object can then be used as follows:

apple.color = "reddish";
alert(apple.getInfo());

Comparison of class-less JavaScript to class-based Java

The following table compares the features of the JavaScript language to the Java language [12].

Table 1: Comparison of class-less JavaScript to class-based Java
Class-based Java Class-less 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 using functions that serve as constructors.
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 a prototype associated with a constructor function.
Inherit properties by following class hierarchy. Inherit properties by following prototype hierarchy.
Class definition specifies all properties of all instances of a class. Properties cannot be added dynamically at run time. Constructor function or prototype specifies an initial set of properties. Properties can be added or removed dynamically to individual objects or to the entire set of objects.


Io

Io is a dynamic prototype-based programming language. The ideas in Io are mostly inspired by Smalltalk[1] (all values are objects), Self (prototype-based), NewtonScript (differential inheritance), Act1 (actors and futures for concurrency), Lisp (code is a runtime inspectable / modifiable tree) and Lua (small, embeddable).

Io's purpose is to refocus attention on expressiveness by exploring higher level dynamic programming features with greater levels of runtime flexibility and simplified programming syntax and semantics. [13]

History of Io

The language was created by Steve Dekorte around March 7, 2002, after trying to help a friend, Dru Nelson, with his language, Cel. He found out that he really didn't know much about how languages worked, and set out to write a tiny language to understand the problems better. [14]

Io and Object Oriented Programming

Io is a prototype-based language. There are no classes and instances; there are only objects.

Objects are typically cloned (from Object or some other existing object) and then extended, i.e. attributes are added to it on the fly. Objects are composed of a list of key/value pairs called slots, and an internal list of objects from which it inherits called protos. A slot's key is a symbol (a unique immutable sequence) and its value can be any type of object.

clone and init

New objects are made by cloning existing ones. A clone is an empty object that has the parent in its list of protos. A new instance's init slot will be activated which gives the object a chance to initialize itself. Like NewtonScript, slots in Io are create-on-write.

 
me := Person clone

To add an instance variable or method, simply set it:

me name := "robert"
me talk := method("I'm talking\n" print)

When an object is cloned, its "init" slot will be called if it has one.

Below is another example that shows how to create a simple object and show how to use it in Io: [15]

Account := Object clone do(
    balance := 0
    deposit  := method(v, balance = balance + v)
    withdraw := method(v, balance = balance - v)
    show := method(writeln("Account balance: $", balance))
)
myAccount := Account clone
myAccount show
"Depositing $10\n" print
myAccount deposit(10)
myAccount show

Inheritance

When an object receives a message it looks for a matching slot, if not found, the lookup continues depth first recursively in its protos. Lookup loops are detected (at runtime) and avoided. If the matching slot contains an activatable object, such as a Block or CFunction, it is activated, if it contains any other type of value it returns the value. Io has no globals and the root object in the Io namespace is called the Lobby. Since there are no classes, there's no difference between a subclass and an instance. Here's an example of creating the equivalent of a subclass:

Io> Dog := Object clone ==> Object_0x4a7c0 The above code sets the Lobby slot "Dog" to a clone of the Object object; the protos list of this new object contains only a reference to Object, essentially indicating that a subclass of Object has been created. Instance variables and methods are inherited from the objects referenced in the protos list. If a slot is set, it creates a new slot in our object instead of changing the protos:

 Io> Dog color := "red"
 Io> Dog
 ==> Object_0x4a7c0:
   color := "red"

Comparison of class-less Io to class-based Java

The following table compares the features of the Io language to the Java language.

Table 2: Comparison of class-based Java to class-less Io [16].
Feature Java Io
Packaging Mechanism Source code separated into packages and compiled classes into jar files. No true packaging mechanism. Source directories can be specified to search for prototype definitions.
Abstraction Mechanisms Objects via instances of static class definitions; Interfaces. Objects via prototyping other objects; No interface construct.
Multiple Inheritance No, although interfaces provide some of the benefits Yes, multiple prototypes are supported, including the addition of new prototypes at runtime.
Garbage Collection Automatic Automatic
Dynamic Programming Read and invocation Read, write, and invocation
GUI Swing and AWT libraries Flux addon

Summary

This topic briefly reviewed features of three Delegation-based programming languages: Lua, JavaScript, and Io. Brief comparisons between these three examples of class-less programming languages versus traditional class-based languages such as C++ and Java were also mentioned in this topic. For additional information regarding the characteristics, classification, and programming constructs of delegation-based (i.e. prototype-based) programming languages, please see this earlier Wiki textbook chapter.

References

[1] Skrien, Dale. Object-oriented Design Using Java. Boston: McGraw-Hill, 2009. Page 239.

[2] http://en.wikipedia.org/wiki/Prototype-based_programming

[3] http://www.lua.org/about.html

[4] http://en.wikipedia.org/wiki/Lua_(programming_language)

[5] http://www.wellho.net/mouth/2701_Is-Lua-an-Object-Oriented-language-.html

[6] http://www.phpied.com/3-ways-to-define-a-javascript-class/

[7] Krill, Paul (2008-06-23). "JavaScript creator ponders past, future". InfoWorld. Retrieved 2009-05-19.

[8] Hamilton, Naomi (2008-06-31). "The A-Z of Programming Languages: JavaScript". computerworld.com.au.

[9] Press release announcing JavaScript, "Netscape and Sun announce Javascript(TM)", PR Newswire, Dec 4, 1995.

[10] "TechVision: Innovators of the Net: Brendan Eich and JavaScript". Web.archive.org. Archived from the original on 2008-02-08. Retrieved 2010-06-14.

[11] http://en.wikipedia.org/wiki/JavaScript Retrieved 2010-11-16.

[12] https://developer.mozilla.org/en/JavaScript/Guide/Details_of_the_Object_Model Retrieved 2010-11-16.

[13] http://www.iolanguage.com/scm/io/docs/IoGuide.html#Introduction-Perspective Retrieved 2010-11-15.

[14] http://en.wikipedia.org/wiki/Io_(programming_language)

[15] http://www.iolanguage.com/about/samplecode/ Retrieved 2010-11-16.

[16] http://www.seas.gwu.edu/~mmburke/courses/csci210-f07/iolang.pdf Retrieved 2010-11-16.