David,

On Oct 11, 2005, at 8:42 PM, Dave Whipp wrote:

Stevan Little wrote:

David,

...
If you would please give a real-world-useful example of this usage of class-methods, I am sure I could show you, what I believe, is a better approach that does not use class methods.

...

The example I've wanted to code in Java is along the lines of:

public class Base {
  public static main(String[] args) {
     init();
     do_it(args);
     cleanup()
  }
}

and then define a bunch of derived classes as my main class.

public class Derived extends Base {
  static init() { print("doing init"); }
  static do_it(String[] args) { print("doing body"); }
  static cleanup() { print("doing cleanup"); }
}

% javac Derived
% java Derived

In other words, I wanted to not have a main function on the class that I run as the application.

This example, of course, doesn't apply to Perl -- but I think that the basic pattern is still useful

I think this example is constrained by the way Java handles the main static method. This same pattern could be done using instance methods, and a little bit of reflection in Java.

public interface Base {
    public void init;
    public void do_it(String[] args);
    public void cleanup;
}

public class BaseRunner {
    public static main (String[] args) {
        ClassLoader cl = new java.lang.ClassLoader();
        Class c = cl.findClass(args[0]);
        Base b = c.newInstance();
        b.init();
        b.do_it(args);
        b.cleanup();
    }
}

public class Derived implements Base {
  public void init() { print("doing init"); }
  public void do_it(String[] args) { print("doing body"); }
  public void cleanup() { print("doing cleanup"); }
}

NOTE: this code is untested :)

This version actually allows you to vary the subclasses though the command line arguments, which provides even greater flexibility and does not require you to recompile BaseRunner or Base.

Doing something similar in Perl 6 is even easier than the Java version.

Stevan







Reply via email to