Facades versus extensions

Should you use a facade or an extension? We think it depends largely upon what "style" of interface you want to provide at the Tcl level. Here's why.

Let's look at this in a little more detail. As we saw, facades have a more object-oriented flavor, and expose the underlying Java to the Tcl programmer. You can, of course, hide the Java-ness by wrapping the facade in a Tcl procedure:

  proc jtimer {mode} {
    global jtimer
    switch -exact $mode {
      "start" {
         if { ![info exists jtimer] } {
	    set jtimer [java::new tutorial.tcltk98.JTimer]
         $jtimer start
      "stop" {
         $jtimer stop
      default {
        error "Must be \"start\" or \"stop\""
This little Tcl proc wraps an instance of the JTimer class and creates a command that is identical in behavior to the JTimerExtension.

If we used the ensemble feature of [incr Tcl], we could it even more concise. Because facades are object-oriented, they also tend to be a good match with [incr Tcl]. (By the way, [incr Tcl] is now a proper dynamically-loadable Tcl extension, and is supported by the Scriptics debugger and tools.) Typically, a single [incr Tcl] object might encase one or more Java objects, providing an extra Tcl layer over the lower-level Java.

We could also have written JTimerExtension so that it made it possible to create and control multiple timers, as we would do with multiple JTimer object. To do so, we would add a new option that creates a new timer, and add an extra argument to the start and stop options, that represents the timer ID. (Much like the Tcl http command suite.)

Above, we mentioned that each call to an extension passes a reference to the Tcl interpreter to the extension. If a facade needs access to a Tcl interpreter, a handle to that interpreter must be explicitly passed to the facade, either in the constructor or as an extra argument to those methods that need it. To get this interpreter, call the java::getinterp procedure. (There is an example of its use in the Events and callbacks section.)