Wednesday, October 01, 2003

Smalltalk: Best Practice Patterns

So, I've been reading Kent Beck's "Smalltalk: Best Practice Patterns". I read it a long time ago and it's good to read it again. I can't recommend it highly enough. I'm amazed at how much I had forgotten, but use subconsciencely. Anyway, a lot of these pattern work in any language, not just Smalltalk. I'm surprised someone hasn't done a version of this in Java or something else.

But, take this example of the "Execute Around Method" pattern in Smalltalk (taken from Kent Beck's book)
    File>>openDuring: aBlock
      self open.
      [aBlock value] ensure: [self close]

Now, I decided to do this in Java, here's the code for the pattern:
    class OurFile {
    ...
    ...
      public openDuring(Runnable aRunnable) throws IOException {
        open();
        try {
          aRunnable.run();

        } finally {
          close();

        }

      }

    ...
    ...
    }
OK, the Smalltalk code is less, but the Java version isn't THAT much more typing now is it? Now, what if we want to use our new method? The Smalltalk code:
    SomeObject>>usePattern: aFile
      aFile openDuring: [Transcript show: 'do something']

Now, look at the Java code:
    public void usePattern(OurFile aFile) throws IOException {
      aFile.openDuring(new Runnable() {
        public void run() {
          System.out.println("Do something");

        }

      }

    }
Ok, my fingers hurt. The Java version requires a lot more typing (keyboard typing that is) than the Smalltalk version. I didn't even get into taking an argument into the block (hint: it might be nice to pass the file). The Smalltalk version would stay the SAME LEGNTH and retain its conciseness and ease of use. The Java version would grow to be quite huge. Why? Because then I would have had to implement a new interface class to take the new argument. And it would also be a good idea to throw an Exception from the Java method in case you didn't want to deal with Exceptions at that level. The Java version looks nice until you have to actually use it.

I've been in Java shops where the use of inner classes like I did here was forbidden. So, to do the above code, I would have had to create a whole new class just so that I could use this pattern. I'm not even going to get into using Java's reflection to use instead. Why? Because it requires EVEN MORE TYPING! It's like the designers of Java didn't want you to do these kinds of things. The kinds of things that make you repeat things once and only once!

No comments:

Amazon