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]
- class OurFile {
...
...
- public openDuring(Runnable aRunnable) throws IOException {
- open();
try {
- aRunnable.run();
} finally {
- close();
}
}
...
...
}
- SomeObject>>usePattern: aFile
- aFile openDuring: [Transcript show: 'do something']
- public void usePattern(OurFile aFile) throws IOException {
- aFile.openDuring(new Runnable() {
- public void run() {
- System.out.println("Do something");
}
}
}
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:
Post a Comment