November 18, 2005 - Influence of Other Languages on Design

The Pragmatic Programmers recommend learning a new language every year. Not because you need to know a whole bunch of languages, but because other languages use idioms that you might not think of using in your everyday language.

I use Java everyday and I had never felt the need to use the visitor pattern. Too much work for too little benefit. After a little Ruby time, I came to appreciate the expressiveness of blocks and tried to emulate the same thing in Java. Hey! That's the visitor pattern! It is useful after all!

Similarly, from C#/.NET, I now write custom collection classes in Java rather than passing plain collections around. Once you thingify an idea, you find all kinds of behavior that belong with that thing. Does your robot need to search its list of enemies to find the closest one? That's behavior that belongs with the list. A little more behavior like that and your "ListOfEnemies" becomes a "FireControlComputer".

From Lisp, I have got in the habit of returning objects from methods that don't strictly need to - which enables method chaining. I might not do it in production code, but it makes for acceptance tests that read very nicely :

results.forTest(test, "deleteImportantFile")

This is a test for a test runner, so it's a little meta. The results for test "deleteImportantFile" should fail with a security exception and the message should contain "important.file".

C# again - I will often replace an if-then-else ladder with a Map containing method objects (delegates in C#). It's a bit more work in Java but it can eliminate a whole lot of duplication and improve coverage. Example :

if(element.getNodeName().equals("a")) {
else if(element.getNodeName().equals("b")) {
/* ... */


Handler handler = handlers.get(element.getNodeName());

Tricks like these are always a little more cumbersome in Java, but once you make the effort to use them, they can make the code much more readable.

Anyone got any more ?

Posted by Kevin Lawrence at November 18, 2005 02:25 PM

Trackback Pings

TrackBack URL for this entry:


Post a comment

Remember Me?