User Tools

Site Tools


at:tutorial:objects

In this section, we explain how the object-oriented programming paradigm is implemented in AmbientTalk.

Objects, fields and methods

In AmbientTalk, objects are not instantiated from classes. Rather, they are either created ex-nihilo or by cloning and adapting existing objects, in the spirit of prototype-based programming such as in the SELF programming language. The definition of a prototypical object contains a number of fields and methods that represent the object's state and behaviour respectively.

The following code illustrates the ex-nihilo creation of an object:

def Point := object: { 
  def x := 0;
  def y := 0;
  def init(aX,aY) {
    x := aX;
    y := aY;
  };
  def sumOfSquares() { x*x + y*y };
}

The above code defines an ex-nihilo created point object and binds it to the variable Point. The object itself does not carry a name (i.e. it is “anonymous”). Like all definitions in AmbientTalk, fields and methods are defined using the def keyword. Fields are defined using a def name := value syntax while methods are defined using a def name(parameters) {body} syntax.

In the example above, the state of the point object is composed of x and y fields while its behaviour corresponds to the init and sumOfSquares methods.

As already explained in the basic programming part of the tutorial, AmbientTalk not only supports traditional canonical syntax (e.g. o.m(a,b,c)) but also keyworded syntax (e.g. o.at: key put: value). Keyworded syntax can be used both for method definitions and for message sends.

For Smalltalk/Self programmers: note that a keyworded message send does require a message sending operator (like .) in between the receiver and the message, which is different from Smalltalk and Self. As will be described in later chapters, AmbientTalk features more than one message sending operator, so the programmer must explicitly specify which one to use.

Sending messages

In AmbientTalk, computation is expressed in terms of objects sending messages to one another. Messages are used to invoke the fields and methods of the objects.

> Point.x
>>0
> Point.sumOfSquares()
>>0

This code shows two messages sent to the point object defined above. The x message acts as an accessor for the x field. The sumOfSquares message looks up the sumOfSquares method in the object and applies it.

Note that the “prototypical” point object defined above can act as a stand-alone object. This is different from a class in a class-based language, which often requires the use of static fields or methods to be used stand-alone.

Cloning and instantiation

As noted above, AmbientTalk objects are created ex-nihilo or by cloning and adapting an existing object. The code below shows the instatiation of a new point object by instantiating the Point prototype:

def anotherPoint := Point.new(2,3)

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:

> anotherPoint.x
>> 2
> Point.x
>> 0
> anotherPoint.x := 3
>> nil
> Point.x
>> 0
AmbientTalk's object instantiation protocol closely corresponds to class instantiation in class-based languages. The major difference lies in the evaluation context of the init method: in a class-based language, the constructor is ran in the context of an empty object, freshly allocated from the class blueprint. In AmbientTalk, the init method is ran in the context of a shallow copy of an original object. Hence, in the init method, fields do not necessarily contain nil values: they have the value of the clonee. This can sometimes be useful to express the state of a clone as a delta w.r.t. the state of its clonee.

AmbientTalk also provides a clone: construct which only creates a clone of the receiver object without calling the init method 1).

def clonedPoint := clone: Point
> clonedPoint.x
>> 0
> clonedPoint.x := 2
>> nil
> Point.x
>> 0

Delegation and Cloning

In order to support code reuse and modular extensions between objects, AmbientTalk features delegation (also known as object-based inheritance). By means of delegation, an object can reuse and extend the fields and methods of another object by establishing a so-called “parent-child” or “delegate-delegator” relationship.

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 (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):

def Point3D := extend: Point with: {
  def z := 0;
  def sumOfSquares() {
    super^sumOfSquares() + z*z;
  };
}

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.

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

def Collection := share: Enumerable with: {
  def elements := [];
  ...
}

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 IS-A and SHARES-A delegation relationships differ in their semantics for cloning child objects. Whereas 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

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.

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 a 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 objects. For example:

def openConnection := object: {
  def send(msg) { ... };
};
def closedConnection := object: {
  def send(msg) { ... };
};
def connection := object: {
  def init() {
    super := closedConnection;
  };
  def open() {
    super := openConnection;
  };
  def close() {
    super := closedConnection;
  };
}

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.

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.

First-class Delegation

AmbientTalk provides a special message-sending operator ^ (the “caret” or “hat” symbol) to express the explicit delegation of a message to an object. The code below illustrates the use of the ^ operator:

def Enumerable := object: {
  def collect: closure {
    def c := self.new([]);
    self.each: { |v|
      c.add(closure(v));
    };
    c;
  };
};
def Array := object: {
  def elements := [];
  def init(a) { elements := a; };
  def add(v) { elements := elements + [v]; self };
  def collect: closure {
    Enumerable^collect: closure;
  };
  def each: clo {
    1.to: elements.length do: { |i|
      clo(elements[i]);
    };
  };
};

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.

Array.add(1).add(2).add(3)
def c := Array.collect: { |v| v+1 }
c.each: { |v| system.print(v)} // prints 234

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 a later chapter, we will show how ^ forms the basis for advanced trait composition.

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:

def Point3D := extend: Point with: {
  def z := 0;
  def init(aX, aY, aZ) {
    super^init(aX, aY);
    z := aZ;
  };
};
AmbientTalk, unlike many other OO languages (including Java and Smalltalk) does not treat super.m(foo) as a special construct. Because 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.

Encapsulation

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 lambda abstraction). The following code shows the definition of an object inside the definition of a function. Although all of the object's 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”:

def makeBankAccount(balance) {
  object: {
    def deposit(amnt) {
      balance := balance + amnt;
      "ok"
    };
  }
}

Because the bank account object encapsulates its balance in its private, lexical scope, the following code fails:

> makeBankAccount(100).balance;
>>Lookup failure : selector balance could not be found in 
  <obj:{super,super:=,deposit}>

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:

def b := makeBankAccount(100);
def b2 := b.new(); // shares its balance field with b!
b.deposit(10); // affects b2 as well!

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:

def makeBankAccount(balance) {
  object: {
    def new(@args) { makeBankAccount(@args) };
    def deposit(amnt) { /* as before */ };
  }
}

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 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:

def o := object: {
  def x := 5
};
> o.x
>> 5
o := object: {
  def x() { 5 }
};
> o.x
>> 5

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:

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

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:

def o := object: {
  def x := { 5 }
};
> o.x
>> <closure:lambda>

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?

> o.x()
>> 5

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:

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

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:

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

If no mutator method is defined, the field assignment will fail with a SelectorNotFound exception.

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.

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

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).
1)
As a matter of fact the new message desribed above does nothing more but invoking this construct and the init method subsequently.
at/tutorial/objects.txt · Last modified: 2013/05/17 20:23 by tvcutsem