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 revision Previous revision
Next revision
Previous revision
at:tutorial:objects [2007/07/18 14:51]
jorge
at:tutorial:objects [2013/05/17 20:23] (current)
tvcutsem updated
Line 159: Line 159:
 def Enumerable := object: { def Enumerable := object: {
   def collect: closure {   def collect: closure {
-    def c := clone: self;+    def c := self.new([]);
     self.each: { |v|     self.each: { |v|
-      c.add(closure(v))+      c.add(closure(v));
     };     };
 +    c;
   };   };
 }; };
 def Array := object: { def Array := object: {
   def elements := [];   def elements := [];
-  def init() { ... };+  def init(a) { elements := a; }; 
 +  def add(v) { elements := elements + [v]; self };
   def collect: closure {   def collect: closure {
     Enumerable^collect: closure;     Enumerable^collect: closure;
Line 173: Line 175:
   def each: clo {   def each: clo {
     1.to: elements.length do: { |i|     1.to: elements.length do: { |i|
-      clo(elements[i])+      clo(elements[i]);
     };     };
   };   };
Line 180: Line 182:
  
 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 above, when ''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. 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 above, when ''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.
 +
 +<code>
 +Array.add(1).add(2).add(3)
 +def c := Array.collect: { |v| v+1 }
 +c.each: { |v| system.print(v)} // prints 234
 +</code>
  
 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//. 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//.
Line 221: Line 229:
 > makeBankAccount(100).balance; > makeBankAccount(100).balance;
 >>Lookup failure : selector balance could not be found in  >>Lookup failure : selector balance could not be found in 
-  <object:5068254>+  <obj:{super,super:=,deposit}>
 </code> </code>
 +
 +This pattern of creating objects by means of "constructor functions" rather than by cloning and instantiating prototypes is often very useful in its own right. However, when creating objects that use their lexical scope to hold their state, be aware of the following issue when you mix object creation via instantiation and object creation via cloning: clones //share// their lexical scope! Hence, given a bank account object ''b'', the following leads to erroneous behaviour:
 +
 +<code>
 +def b := makeBankAccount(100);
 +def b2 := b.new(); // shares its balance field with b!
 +b.deposit(10); // affects b2 as well!
 +</code>
 +
 +In order to prevent this kind of errors, it is considered best practice to override ''new'' for objects that should be solely defined by means of constructor functions, as follows:
 +
 +<code>
 +def makeBankAccount(balance) {
 +  object: {
 +    def new(@args) { makeBankAccount(@args) };
 +    def deposit(amnt) { /* as before */ };
 +  }
 +}
 +</code>
 +
 +By overriding ''new'' and calling the constructor function, this code ensures that code such as ''aBankAccount.new(10)'' will result in a proper new bank account object with its own private lexical scope to store its state.
 +
 +===== Uniform Access =====
 +
 +AmbientTalk inherits from languages like Self, Eiffel and Ruby the property that field access is made indistinguishable from invoking a nullary method. This property is often referred to as the [[Wp>Uniform_access_principle|uniform access principle]], a term coined by Bertrand Meyer. In essence, the principle allows designers of abstractions to freely change public fields into methods that take no arguments, and vice versa **without** requiring changes to client code that uses the abstraction. The following example illustrates the essence of the UAP:
 +
 +<code>
 +def o := object: {
 +  def x := 5
 +};
 +> o.x
 +>> 5
 +o := object: {
 +  def x() { 5 }
 +};
 +> o.x
 +>> 5
 +</code>
 +
 +Hence, the general rule is that ''o.x'' is equivalent to ''o.x()''. Importantly, this principle also holds for //lexical// resolution of variables, rather than dynamic resolution via message sending. For example:
 +
 +<code>
 +def o := object: {
 +  def x := 5
 +  def xPlus1() { x + 1 }
 +};
 +> o.xPlus1
 +>> 6
 +o := object: {
 +  def x() { 5 }
 +  def xPlus1() { x + 1 }
 +};
 +> o.xPlus1
 +>> 6
 +</code>
 +
 +Note that the variable lookup ''x'' is treated as ''x()'' when the variable refers to a lexically visible //method// rather than a //field//. This is useful because it allows changing fields into methods or vice versa without even affecting nested objects making use of the abstraction.
 +
 +==== UAP and closures ====
 +
 +One may wonder how the uniform access principle interacts with closures. That is, if ''x'' is a field whose value is a block closure, does ''o.x'' return the closure or does it implicitly apply that closure with zero arguments, as it does if ''x'' were bound to a method? The answer is no:
 +
 +<code>
 +def o := object: {
 +  def x := { 5 }
 +};
 +> o.x
 +>> <closure:lambda>
 +</code>
 +
 +The rationale is that ''x'' is bound to a field, so performing ''o.x'' simply selects the value from the field. However, what happens if we evaluate ''o.x()'' instead?
 +
 +<code>
 +> o.x()
 +>> 5
 +</code>
 +
 +When explicitly //applying// the ''x'' field, the interpreter //does// execute the block closure stored in ''x''. If the interpreter would not behave in this way, but rather have ''o.x()'' return the closure as well, then the programmer would be required to write ''(o.x)()'' to apply the closure, which is a bit clumsy. In essence, the rule remains simple: code of the form ''o.x'' either returns the value of a //field// ''x'' or executes a //method// ''x''. Whether or not the field contains a closure does not change the semantics.
 +
 +==== UAP and Assignment ====
 +
 +In order to uphold the uniform access principle, special care is required with respect to assignment. If clients should be fully able to abstract over the implementation of slots as either fields or accessor methods, it should be possible to unify field assignment with mutator invocation. In AmbientTalk, mutators are methods whose name ends with '':=''. These methods take one argument and can be invoked by means of the field assignment syntax:
 +
 +<code>
 +def realField := 5;
 +def o := object: {
 +  def virtualField() { realField };
 +  def virtualField:=(v) { realField := v }; 
 +};
 +> o.virtualField
 +>> 5
 +> o.virtualField := 3 // interpreted as o.virtualField:=(3)
 +>> 3
 +</code>
 +
 +In essence, assigning the field of an object is treated as a message send triggering a mutator method. Here's a more useful example of virtual fields:
 +
 +<code>
 +def time := object: {
 +  def seconds := 60;
 +  // a field implicitly represents an accessor method seconds()
 +  // and a mutator method seconds:=(v)
 +
 +  def minutes() { seconds / 60 };
 +  def hours()   { seconds / 3600 };
 +
 +  def minutes:=(mins) {
 +    seconds := mins * 60; mins
 +  };
 +  def hours:=(hours) {
 +    seconds := hours * 3600; hours
 +  };
 +};
 +> time.minutes
 +>> 1
 +> time.hours := 1
 +>> 1
 +> time.seconds
 +>> 3600
 +> time.seconds := 180
 +>> 180
 +> time.minutes
 +>> 2
 +</code>
 +
 +If no mutator method is defined, the field assignment will fail with a ''SelectorNotFound'' exception.
 +
 +<note>
 +AmbientTalk has no direct notion of ''final'' or constant variables. However, if read-only access to a field for clients is required, one can simply implement the "field" as an accessor method. In this way, the method can be invoked as if it were a field, but any attempt to assign the field will fail because no corresponding mutator has been defined.
 +</note>
 +
 +The uniform access principle for assignments equally holds for lexically visible methods. In other words, the code ''x := 5'' is interpreted as a //function call// ''x:=(5)'', just as the assignment ''o.x := 5'' is interpreted as a //message send// ''o.x:=(5)''.
 +
 +<note warning>
 +The parser currently does not support the explicit invocation of a mutator as a method or function (as in ''o.m:=(v)''). To invoke a mutator, always use the field assignment syntax (as in ''o.m := v'').
 +</note>
at/tutorial/objects.1184763075.txt.gz · Last modified: 2007/07/18 18:09 (external edit)