User Tools

Site Tools


at:tutorial:objects

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
at:tutorial:objects [2007/07/09 21:25] – explained tvcutsemat:tutorial:objects [2007/07/18 14:51] jorge
Line 51: Line 51:
 </code> </code>
  
-Every object understands the message ''new'', which creates a clone (a shallow copy) of the receiver object and initializes the clone by invoking its ''init'' method with the arguments that were passed to new (''aX'' and ''aY'' in the example code). Hence, the ''init'' method plays the role of "constructor" for AmbientTalk objects. Hence, in the code above, ''anotherPoint'' shares its methods with its ''Point'' prototype, but it has its own set of fields:+Every object understands the message ''new'', which creates a clone (a shallow copy) of the receiver object and initializes the clone by invoking its ''init'' method with the arguments that were passed to new (''aX'' and ''aY'' in the example code). Hence, the ''init'' method plays the role of "constructor" for AmbientTalk objects. In the above code, ''anotherPoint'' shares its methods with its ''Point'' prototype, but it has its own set of fields:
  
 <code> <code>
Line 86: Line 86:
 Delegation implies that, if a message is sent to an object, but that object has no definition for the message's selector, then the message is //delegated// to a designated object (often called the //parent// or //delegate//). What is important to note here is that "delegating" a message is not the same as simply "forwarding" the message to the other object: delegating a message leaves the ''self'' pseudovariable unchanged to the //original// receiver of the message. Delegation implies that, if a message is sent to an object, but that object has no definition for the message's selector, then the message is //delegated// to a designated object (often called the //parent// or //delegate//). What is important to note here is that "delegating" a message is not the same as simply "forwarding" the message to the other object: delegating a message leaves the ''self'' pseudovariable unchanged to the //original// receiver of the message.
  
-AmbientTalk distinguishes between **two kinds** of delegation relationships,**IS-A** and **SHARES-A**, each denoting a different kind of object extension. An **IS-A** delegation relationship between two objects signifies that the child object "is-a" kind of parent object, with the implicit assumption that such a child object cannot exist without its parent. As an example, consider the following code (don't worry about the meaning of ''^'' yet):+AmbientTalk distinguishes between **two kinds** of delegation relationships,**IS-A** and **SHARES-A**, each denoting a different kind of object extension (the difference between both is explained below). 
 + 
 +An **IS-A** delegation relationship between two objects signifies that the child object "is-a" kind of parent object, with the implicit assumption that such a child object cannot exist without its parent. As an example, consider the following code (don't worry about the meaning of ''^'' yet):
  
 <code> <code>
Line 92: Line 94:
   def z := 0;   def z := 0;
   def sumOfSquares() {   def sumOfSquares() {
-    super^sumOfSquares() + z*z +    super^sumOfSquares() + z*z; 
-  }+  };
 } }
 </code> </code>
  
-In this example, ''Point3D'' delegates+In this example, ''Point3D'' delegates any message it does not understand to ''Point''. The ''extend:with:'' construct creates a new object whose ''super'' slot is automatically set to the given parent object. The delegation relationship is **IS-A** because a ''Point3D'' is a kind of 2D ''Point'', and a ''z'' coordinate (conceptually) cannot exist without a corresponding ''x'' and ''y'' coordinate.
  
-These relationships define two different semantics for clonning child objects. Whereas clonning a **IS-A** child also clones its parent, **SHARE-A** child shares the parent of the cloned object (see the figure below).+**SHARES-A** relationship between two objects signifies that an object only delegates to another object purely for reasons of code or state sharing. The delegation link has no other semantics, and conceptually both parent and child can exist without one another.
  
 +The following code shows how to extend objects with a **SHARES-A** delegation relationship. It uses the ''share: with:'' language construct.
  
-{{:at:tutorial:isaversussharea.png|:at:tutorial:isaversussharea.png}}+<code> 
 +def Collection := shareEnumerable with
 +  def elements := []; 
 +  ... 
 +} 
 +</code>
  
 +In this code example, the ''Collection'' object delegates to ''Enumerable'' simply for inheriting useful methods such as ''inject:'' or ''collect:'' which are of general use to a collection object.
  
-The following code shows how to extend objects with a **IS-A** relationshipIt uses the ''extend: with:'' language construct.+The **IS-A** and **SHARES-A** delegation relationships differ in their semantics for cloning child objectsWhereas cloning an **IS-A** child also clones its parent, a **SHARES-A** child shares its parent object with the clonee (see the figure below).
  
 +{{:at:tutorial:isaversussharea.png|:at:tutorial:isaversussharea.png}}
  
 +This cloning semantics reinforces the semantics of **IS-A** as promoting a unique link between a parent and a child object. **IS-A** delegation most closely corresponds to class-based inheritance.
  
-The following code shows how to extend objects with **SHARE-A** relationshipIt uses the ''share: with:'' language construct.+===== Delegation and Dynamic Inheritance ===== 
 + 
 +In AmbientTalk, all objects delegate messages they cannot understand to the object stored in their field named ''super''. The delegation chain defined by an object and its parent (or chain of parents) determines the scope in which message is looked up. For ex-nihilo created objects, like the ''Point'' object defined previously, the ''super'' slot is by default set to ''nil''When a message is finally delegated all the way up to ''nil'', ''nil'' informs the original receiver of the message of the failed lookup, which by default reports the error by means of a ''SelectorNotFound'' exception. 
 + 
 +Because ''super'' is a regular field of an AmbientTalk object (it is just installed by default), it can be dynamically modified, giving rise to //dynamic inheritance//: the ability of objects to change their object inheritance hierarchy at runtime. The SELF language has demonstrated how this language feature can be put to good use for modeling stateful objectsFor example:
  
 <code> <code>
-def point3D := share: point with: { +def openConnection := object: { 
-    def := 0+  def send(msg) { ... }; 
-    def sumOfSquares() { +}; 
-      super^sumOfSquares() + z*z +def closedConnection := object: { 
-    } +  def send(msg) { ... }
-  }+}; 
 +def connection := object: { 
 +  def init() { 
 +    super := closedConnection; 
 +  }; 
 +  def open() { 
 +    super := openConnection; 
 +  }; 
 +  def close() { 
 +    super := closedConnection; 
 +  }; 
 +}
 </code> </code>
  
-===== Delegation and dynamic inheritance ===== +In the above example, the ''connection'' object can be in an "open" or "closed" state. Rather than implementing the state-specific behaviour of e.g. the ''send'' method by means of a state variable and an ''if''-test, state-specific methods are implemented in dedicated objects which are dynamically assigned as the parent of the ''connection'' object when it changes state. When ''connection.send(msg)'' is evaluated, the ''send'' message is delegated to the parent, resulting in the application of the method in the correct state. 
-The parent of an object is bound to field named ''super''. The delegation chain defined by an object and its parent (or chain of parentsdetermines the scope in which the message is looked upAs any field in AmbientTalk objects, the ''super'' field can be dynamically modified.+ 
 +<note> 
 +In AmbientTalk, ''self'' and ''super'' indicate the receiver object and the parent respectively. However, ''self'' is a pseudovariable: it is a special keyword, not a variable that can be assigned to. ''super'' on the other hand, denotes a regular field in an object. This is a significant difference with respect to many other object-oriented languages who also treat ''super'' as a special keyword. There is, however, a reason for this special treatment of ''super'': "super-sends". The repercussions of AmbientTalk's treatment of ''super'' on "super-sends" is discussed below. 
 +</note> 
 + 
 +===== First-class Delegation ===== 
 + 
 +AmbientTalk provides special message-sending operator ''^'' (the "caret" or "hat" symbolto express the //explicit// delegation of a message to an objectThe code below illustrates the use of the ''^'' operator:
  
 <code> <code>
-def openConnection := object: {...}; +def Enumerable := object: { 
-def closedConnection := object: {...}; +  def collectclosure 
-def connection := object{ +    def := cloneself; 
-    def open() +    self.each: |v| 
-      super := openConnection.new();+      c.add(closure(v))
     };     };
-    def close() { +  }; 
-      super := closedConnection.new();+}; 
 +def Array := object: { 
 +  def elements := []; 
 +  def init() { ... }; 
 +  def collectclosure { 
 +    Enumerable^collect: closure; 
 +  }; 
 +  def each: clo { 
 +    1.to: elements.length do: { |i| 
 +      clo(elements[i])
     };     };
-  }+  }
 +};
 </code> </code>
  
-<note important> +A message sent to an object using the ''^'' symbol (e.g. to the ''Enumerable'' object in the example above) will start the method lookup in this object and execute the method body with the ''self'' pseudovariable **left unchanged** to the message sender. In the code example abovewhen ''collect:'' is invoked on an ''Array'' object, the array object //delegates// the message to the ''Enumerable'' object. As such, method lookup starts in ''Enumerable'', finds the method there, and then invokes it with ''self'' left bound to the ''Array'' object. Hence, the ''self.each:'' send in the ''Enumerable'' object uses ''Array'''s definition of ''each:'' to generate the elements in the collection.
-In AmbientTalk, ''self'' and ''super'' indicate the current object and its parent respectivelyWhile the former corresponds to a language keyword the latter is just a field name of the object. +
-</note>+
  
-===== First-class delegation ===== +Of course, the example above is a bit contrived: we could have just assigned ''Enumerable'' as the parent of ''Array'' such that we would not even have to write the "delegating''collect:'' method in ''Array''However, what the explicit ''^'' delegation operator allows is the expression of patterns resembling //multiple inheritance// where some requests are delegated to one object, while other methods can be delegated to other objects. Explicit delegation enables the expression of delegation patterns which would be awkward or difficult to express using only single (delegation-based) inheritance. In [[:at:tutorial:modular#objects_as_traits|a later chapter]], we will show how ''^'' forms the basis for advanced //trait composition//
-AmbientTalk provides an explicit delegation operator ''^'' (the "caretor "hat" symbol)The code below illustrates the use of the ''^'' operator in the implementation of the ''init'' method of the ''point3D'' object.+ 
 +Having described the semantics of ''^'', we can now turn our attention to "super-sends". In AmbientTalk, a traditional "super-send" (ala Java or Smalltalk) is expressed as explicit delegation to the ''super'' object. For example, here is how to properly initialize parent objects from child objects:
  
 <code> <code>
-def point3D := extend: point with: { +def Point3D := extend: Point with: { 
-    def z := 0; +  def z := 0; 
-    def init(aX, aY, aZ) { +  def init(aX, aY, aZ) { 
-      super^init(aX, aY); +    super^init(aX, aY); 
-      z := aZ; +    z := aZ; 
-    }; +  }; 
-  }+};
 </code> </code>
- 
-A message sent to an object using the ''^'' symbol (e.g. to the parent object in the example above) will start the method lookup in this object (and its parents) and then execute the method body in the lexical scope of the message sender (''self'' is bound to the message sender). 
  
 <note warning> <note warning>
-The delegation operator does not have the same semantics as the dot notationA message sent to ''super'' using the dot notation will not only start the method lookup in the object bound the ''super'' field but also bind the ''self'' pseudo variable to this object.+AmbientTalk, unlike many other OO languages (including Java and Smalltalk) does not treat ''super.m(foo)'' as a special constructBecause AmbientTalk regards ''super'' as a regular field name, and because it distinguishes invocation from delegation by means of ''.'' vs ''^'', super-sends can be expressed without any special additions as ''super^m(foo)''
 + 
 +Keep in mind, however, that ''super.m(foo)'' is //not// a "super-send" in the traditional sense of the word. Rather, it is a method invocation on ''super'', changing the value of ''self'' in ''m'' to refer to ''super''.
 </note> </note>
  
 ===== Encapsulation ===== ===== Encapsulation =====
-In AmbientTalk, all fields and methods are "public" via selectionStill, a field or method can be made "private" by means of lexical scoping. The following code shows the definition of an object inside the definition of a function. The fields and methods of this object cannot be accessed directly from outside the funuction.+ 
 +AmbientTalk has no notion of "visibility modifiers" for fields or methods. All fields and methods of an object are considered "public"Nevertheless, a field or method can be made "private" to a scope by means of lexical scoping (a technique sometimes referred to as [[http://www.erights.org/elib/capability/ode/ode-objects.html|lambda abstraction]]). The following code shows the definition of an object inside the definition of a function. Although all of the object'fields and methods are public, the object can make use of lexically visible fields and methods of outer objects or functions which are not simply accessible "from the outside":
  
 <code> <code>
-def makeObject(hidden) { +def makeBankAccount(balance) { 
-    object: { +  object: { 
-      def foo() { /* use hidden */ } +    def deposit(amnt) { 
-    }+      balance := balance + amnt; 
 +      "ok" 
 +    };
   }   }
 +}
 </code> </code>
  
-Due to the encapsulation of this object the following instruction fails:+Because the bank account object encapsulates its ''balance'' in its private, lexical scope, the following code fails:
  
 <code> <code>
-makeObject(5).hidden+makeBankAccount(100).balance
->>Lookup failure : selector hidden could not be found in +>>Lookup failure : selector balance could not be found in 
   <object:5068254>   <object:5068254>
 </code> </code>
at/tutorial/objects.txt · Last modified: 2013/05/17 20:23 by tvcutsem