Monday, October 7, 2013

ELENA 2.0 Tutorial: Add a variable to a class instance at runtime

In this tutorial we will implement Rosetta code sample - Add a variable to a class instance at run-time.

Though ELENA does not allow directly adding a field / method to the object it is possible dynamically to override any object with a help of the redirect method.

Let’s declare a wrapper class which will bind our class instance with a variable.

class Extender
{
    object theObject.
    object theField.
    
    constructor new : anObject
    [
        theObject := anObject.
    ]
    
    foo = theField.
    
    set &foo : aValue
    [
        theField := aValue.
    ]
}

The code is simple: we declare a field and two methods accessing it: get&foo and set&foo: and an initializing constructor.

Now let’s declare a redirect method:

dispatch => theObject.

This method will redirect any unhandled message to the field - theObject. As a result we effectively dynamically override the object (so called horizontal inheritance).

Now let’s test the code:

    var anObject := Extender new:234.

    anObject set &foo:"bar".

    console << anObject << ".foo=" 
            << anObject foo.

The output will be the following:

234.foo=bar

The full tutorial code is below:

class Extender
{
    object theObject.
    object theField.
    
    constructor new : anObject
    [
        theObject := anObject.
    ]
    
    foo = theField.
    
    set &foo : aValue
    [
        theField := aValue.
    ]
    
    dispatch => theObject.
}

symbol program =
[
    var anObject := 234.
  
    // adding a field
    anObject := Extender new:anObject.

    anObject set &foo:"bar".

    console << anObject << ".foo=" 
            << anObject foo.

    console readChar.
].