Automatic get/set methods for an itcl class

As the itcl::class is a tcl command, you can insert code into the class declaration.

It is common C++ practice to have set/get methods to protect the variables in an object from manipulation outside the class.

This sample class creates a set of methods to set and enquire a list of protected variables.

  console show
  package require Itcl
  itcl::class tclass {
      foreach v {time distance} { 
        method get$v {} [subst -nocommands { return [subst $$v] }]
        method set$v nuval [subst -nocommands { set $v \$nuval } ]
        protected variable $v "Var $v"
      constructor {} { puts "Constructs $this" }
      method speed {} { return [expr {[getdistance]/[gettime]}]}
  tclass a
  a setdistance 2
  a settime 3.0
  puts "Travelled [a getdistance] taking Time [a gettime] so speed is [a speed]"

The variable list can be arbitrarily long of course when this would save considerable typing and validation effort. The code can include any of the itcl::class constructs. If you wish the variable list to be a variable in the class then it must be a common variable so that it is available at class creation time:

  itcl::class tclas2 {
      common vars {time distance power}
      foreach v $vars { 
        method get$v {} [subst -nocommands { return [subst $$v] }]
        method set$v nuval [subst -nocommands { set $v \$nuval } ]
        protected variable $v "Var $v"
      constructor {} { puts "Constructs tclas2 $this" }
      method showVarsandMethods {} { puts "Variables with get/set methods exist for: $vars.\nMethods are: [info function]" }
  tclas2 b
  b showVarsandMethods 

This example shows that setpower, getpower, set/getdistance and set/gettime are all methods of the class tclas2 even though the functions are not explicitly declared.

Entered by GWM.

GWM an improvement places the make get and set methods in a proc 'makegetset' which can be referred to by all classes in a program.

  proc makegetset {args} {
    foreach {vn val} $args {
    uplevel 1 public variable $vn $val
      uplevel 1 public method set$vn \{v\} \{[subst -nocommand {set $vn \$v}] \}
      uplevel 1 public method get$vn \{\} \{[subst -nocommand {return $$vn}]\}        
  itcl::class BarBar {
         eval makegetset {foo 9 foot 2 frob 6}
         constructor {} {}
  set o [BarBar #auto]
  puts "In $o foo is [$o getfoo] foot is [$o getfoot] and frob [$o getfrob]"
  $o setfoo 355
  $o getfoo