Any particular method implementation always comes as late in the resulting list of implementations as possible.
Each filter should decide for itself whether to permit the execution to go forward to the proper implementation of the method (which it does by invoking the next command as filters are inserted into the front of the method call chain) and is responsible for returning the result of next.
Filters are not invoked when processing an invokation of the unknown method because of a failure to locate a method implementation, or when invoking either constructors or destructors.
oo::class create theSuperclass {
method example {args} {
puts "in the superclass, args = $args"
}
}
oo::class create theSubclass {
superclass theSuperclass
method example {args} {
puts "before chaining from subclass, args = $args"
next a {*}$args b
next pureSynthesis
puts "after chaining from subclass"
}
}
theSubclass create obj
oo::define obj method example args {
puts "per-object method, args = $args"
next x {*}$args y
next
}
obj example 1 2 3
prints the following:
per-object method, args = 1 2 3 before chaining from subclass, args = x 1 2 3 y in the superclass, args = a x 1 2 3 y b in the superclass, args = pureSynthesis after chaining from subclass before chaining from subclass, args = in the superclass, args = a b in the superclassm args = pureSynthesis after chaining from subclass
This example demonstrates how to build a simple cache class that applies memoization to all the method calls of the objects it is mixed into, and shows how it can make a difference to computation times:
oo::class create cache {
filter Memoize
method Memoize args {
# Do not filter the core method implementations
if {[lindex [self target] 0] eq "::oo::object"} {
return [next {*}$args]
}
# Check if the value is already in the cache
my variable ValueCache
set key [self target],$args
if {[info exist ValueCache($key)]} {
return $ValueCache($key)
}
# Compute value, insert into cache, and return it
return [set ValueCache($key) [next {*}$args]]
}
method flushCache {} {
my variable ValueCache
unset ValueCache
# Skip the cacheing
return -level 2 ""
}
}
oo::object create demo
oo::define demo {
mixin cache
method compute {a b c} {
after 3000 ;# Simulate deep thought
return [expr {$a + $b * $c}]
}
method compute2 {a b c} {
after 3000 ;# Simulate deep thought
return [expr {$a * $b + $c}]
}
}
puts [demo compute 1 2 3] → prints "7" after delay
puts [demo compute2 4 5 6] → prints "26" after delay
puts [demo compute 1 2 3] → prints "7" instantly
puts [demo compute2 4 5 6] → prints "26" instantly
puts [demo compute 4 5 6] → prints "34" after delay
puts [demo compute 4 5 6] → prints "34" instantly
puts [demo compute 1 2 3] → prints "7" instantly
demo flushCache
puts [demo compute 1 2 3] → prints "7" after delay