From: Will Duquette Date: May 9, 2004 4:45:50 PM PDT To: snit@lists.wjduquette.com Subject: Snit Reconsidered #4: Default Methods (This is the fourth in a series of essays I'll be writing in preparation for the design and implementation of Snit 1.0. Please comment!) Snit 1.0 will likely include a mechanism to define a type's "default method". The default method can be called by name, just as any method can; in addition, it will be called when the instance command is invoked without a method. It practice, it might look like this: % snit::type friendlydog { method bark {{times 1}} { puts "Woof!" } defaultmethod wagtail { puts "Wag, wag, wag." } } ::friendlydog % friendlydog spot ::spot % spot bark 2 Woof! Woof! % spot wagtail Wag, wag, wag. % spot Wag, wag, wag. % As shown in the last command, entering "spot" with no arguments automatically invoked the default method. If no default method had been defined, then invoking "spot" by itself would get the same response Snit gives now in similar circumstances. I find this idiom useful in cases where the object represents a single (possibly complex) piece of data that can be represented as a Tcl string but that has a number of things that can be done to it. In this case, the object's methods represent the valid operations, and the default method can return the value as a string. Consider the following partial type definition: % snit::type complex { variable real ;# The real part variable imag ;# The imaginary part constructor {initialValue} { # Omitted: checks value, which must have form "A+Bi" where # "A" and "B" are decimal strings, and sets real and imag. } defaultmethod value { return "$real+${imag}i" } } method := {newValue} { # Omitted: checks value, which must have form "A+Bi" where # "A" and "B" are decimal strings, and sets real and imag. } method real {} { return $real } method imag {} { return $imag } } % complex x 5+3i 5+3i % x 5+3i % x value 5+3i % x := 2+7i 2+7i % x real 2 % x imag 7 % complex y [complex expr {([x] + [x]) * ([x] - 5i)}] .... This idiom allows the value to be validated on set, and queried in a variety of interesting ways, while still making the most typical query very easy. ------------------------------------------------------------- will -at- wjduquette.com | Catch our weblog, http://foothills.wjduquette.com | The View from the Foothills