Version 3 of oo::configurable

Updated 2023-05-24 17:03:07 by dkf

The oo::configurable class is a part of TclOO in Tcl 8.7. It is a metaclass, i.e., it modifies how you create classes, adding the capability to define properties on the class. It also modifies the class to add a configure method (via a mixin). The configure method is aware of the properties defined across the inheritance hierarchy for the class.

Examples

In particular, this means that if one does:

oo::configurable create Point {
    property x y
    constructor args {
        my configure -x 0 -y 0 {*}$args
    }
    variable x y
    method print {} {
        puts "x=$x, y=$y"
    }
}

You can then do:

set pt [Point new -x 27]
$pt print;   # x=27, y=0
$pt configure -y 42
$pt print;   # x=27, y=42
puts "distance from origin: [expr {
    hypot([$pt configure -x], [$pt configure -y])
}]";         # distance from origin: 49.92995093127971
puts [$pt configure]
             # -x 27 -y 42

That can then be extended with more properties by a subclass:

oo::configurable create Point3D {
    superclass Point
    property z
    constructor args {
        next -z 0 {*}$args
    }
}

set pt2 [Point3D new -x 2 -y 3 -z 4]
puts [$pt2 configure]
              # -x 2 -y 3 -z 4

# How it works oo::configurable is a metaclass that does two things:

  1. It mixes the oo::configuresupport::configurable class into your class definition; that class contains the definition of the configure method.
  2. It sets up definition namespaces so you can say property in your definitions. That's in turn currently ultimately handled by the oo::configuresupport::PropertyImpl procedure, but that's subject to change.