Java anonymous classes are too verbose

Java doesn’t have first-class functions or closures, but you can emulate some of that with anonymous classes. Alas, they are just too cumbersome and verbose—it’s not elegant anymore if you need more LoC than with the iterative loop.

Recently at work, I wanted to execute some code for each member of a List, and I needed to know which iteration step I was at. A straightforward solution is, obviously, the classic for loop:

for (int i = 0; i < keyword.getSynonyms(); i++) {
    String synonym = keyword.getSynonyms().get(i);
    // do something

That’s fine in many cases, but it has two problems. The extra line to get at the List element is annoying. More importantly, depending on the List implementation the get(i) operation might be in O(n), requiring another scan of the list each time.

So we could iterate normally and count ourselves:

int order = 0;
for (String synonym : keyword.getSynonyms())
    // do something

It’s better, but I needed several such loops, and I wondered if I couldn’t write all that plumbing just once. I came up with this:

public abstract class Counting<T, E extends Throwable>
    public void loop(Iterable<T> things) throws E
        int step = 0;
        for (T t : things)
            iteration(t, step);

    public abstract void iteration(T thing, int step) throws E;

As the loop body can throw exceptions, and we might want to declare the specific kind of exception, this needs to be an additional generic type. This breaks if you need more than one exception type.

The above loop then becomes

new Counting<String, SQLException>()
    @Override public void iteration(String synonym, int step)
        throws SQLException
        // do something
}.loop( keyword.getSynonyms() );

Hmmm. Even after writing an abstract class to extract the repeated parts, and not counting my preference for opening-brace-on-new-line, I still haven’t saved a single line. Can I have map and first-class functions, please? Time for Scala?

FrOSCamp 2010 Zuerich

So, another one of those belated meeting/event reports: on 2010-09-17, I was in Zurich for the first-ever FrOSCamp. It was an Open Source/Free Software event with an exhibition floor, talks, and “a fancy party with creative commons licensed beer and music”—what’s not to like!

I presented my “Praktisches RDF in Perl” talk that I recycled from the German Perl Workshop, to spread the word some more. This time, I had prepared an English version, but as I only had German speakers in the audience, I presented in German.

Unfortunately my presentation only drew a handful of people this time. Note to self: work on the abstract some more. I had suspected that my FrOSCamp one was wordy and not catchy, but didn’t get around to rewriting it. At least the audience were pretty engaged and asked lots of questions, which I prefer to a larger crowd that’s half asleep.

The presentation was recorded and is now online as slides+audio. This was a first for me. I could forget about it while presenting, but I was pretty nervous listening to it for the first time, not sure what mess of incoherent rambling and half-finished sentences to expect. Fortunately, I found it ok in the end. Of course, I found several things to improve, but I guess that’s expected for someone who doesn’t present often and is just getting started. My list of the main points to improve is:

  • The introduction should be much shorter and more focussed. A bit like a sales pitch, not as in being obnoxious and fake, but as in focussed on getting the audience’s attention and appreciation for the topic.
  • Too many sentences didn’t flow properly. Simply doing one or two more dry runs should fix that.
  • Have some more visualizations such as diagrams on the slides.

On the other hand, I was pleased with a few things about my presentation: the style of having little text on the slides and more verbal explanation worked well, the code samples seemed to be the right size to digest during a talk, and the questions at the end showed that people had gotten the key points.

Before my presentation, I got to see Renee Baecker‘s talk about Perl::Critic. I’m using it on my code and thus knew the basics, but I appreciated the advanced example towards the end, where Renee walked us through writing our own critic rules. This works via PPI, so you can find patterns in the AST that match the constructs you want to check. I also found it interesting to hear Renee’s personal experience with the severity levels: he’s typically on 3, sometimes 2, but 1 is too harsh.

Other than that, I was mainly hanging out at the Perl booth, a first for me! The booth was staffed by Renee and Roman from Winterthur (CH), two really nice guys whom I had a great time with, discussing everything from Perl modules to freelancing.

BTW, remember the blurb from the FrOSCamp website I quoted at the top about creative commons licensed beer? That wasn’t a joke. FreeBeer is an organic beer, produced by an independent brewery near Zurich, and the recipe is online under a CC license. And it tastes great! A cloudy, full blonde just how I like it :-)

Simple Frame Initialization

Is anyone else confused by the variety and complexity of packages for Emacs session management out there? I read through some of the documentation recently, but in the end I was overwhelmed and didn’t install anything.

Session management is about open files, buffer positions and the like on the one hand, and about the frame configuration on the other hand. I realized that my actual use case for frame session management was so simple that I could trivially implement it myself.

All I really wanted was that my Emacs would launch in fullscreen, and split it into two or three vertical windows, depending on whether I was using the laptop screen or the larger external screen. If I could accept the two-split as default, and run a function to create the three-window setup when needed, then all I’d need were some small initialization functions.

Like almost everything else, Emacs exposes its window and frame handling in an ELisp API. So here we go:

(defun my-big-screen ()
  "Set up frame for external screen, with three windows."
  (my-initialize-frame 3))

(defun my-small-screen ()
  "Set up frame for laptop screen, with two windows."
  (my-initialize-frame 2))

(defun my-initialize-frame (columns)
  "Set current frame to fullscreen and split it into COLUMNS
vertical windows."
  (set-frame-parameter nil :fullscreen t)
  (dotimes (not-used (1- columns))

This is not rocket science and I hope it didn’t bore the Planet Emacsen readers, but maybe it encourages people to get creative with their Emacs’ frames and windows. Start with the Emacs Lisp manual, chapters 28 (Windows) and 29 (Frames).

Java memory problems

At work, I recently wrote up a page for our internal wiki about Java memory problems and how to debug them. It’s quite simplified and short as it’s geared towards beginning or intermediate Java developers. Nevertheless it might be useful to someone out there.

We first look at the most essential Java memory basics, then see how we can track down out-of-memory problems. I’ve thrown in the most useful references.

Continue reading “Java memory problems”

Announcing delim-kill.el

A few weeks ago, I had the chance to attend a few courses on Perl and one on giving technical presentations, held by Perl guru and uber-geek Damien Conway. They were fantastic—just like the ones last year—so I should really write a post of its own about them. Strongly recommended.

But for now, this is about one particular thing he said about editing: you need to have a shortcut in your editor that cuts or copies the text between two given characters around cursor, or point in Emacs lingo. This lets you do many frequent editing tasks easily. Say you’re going through a source file and want to move {}-delimited blocks around, or copy the field you’re on in a CSV file, or the current section in a Markdown file (from # to the next #, roughly).

Damian showed this off in Vim. I knew right away that I wanted it in Emacs. There are of course specialized functions for doing things with certain groups of delimiters, such as the ubiquitous sexp-based functions in Emacs, described extensively on the EmacsWiki. But these rely on pre-configured groups of delimiters, and to kill the text, you have to do one extra operation. I liked the idea of having a single function, and thus key binding, to do all of it. And most importantly, it seemed an interesting challenge for my still-developing Emacs and Lisp skills, so I didn’t even do a lot of research before I dug right in and wrote delim-kill.el.

delim-kill.el contains a single convenience function for editing structured data: delim-kill. Given two characters FROM and TO, delim-kill kills the text between the first occurrence of FROM before point and the first occurrence of TO after point. FROM and TO may be identical.

If FROM and TO are not identical, the function preserves the balance between the two characters: For each FROM that is encountered while looking for TO, one additional TO is required; and vice versa. For example, in “{ foo X{bar} baz }”, with X being point and “{” and “}” as delimiters, the text “{ foo {bar} baz }” will be killed, not “{ foo {bar}”.

I had fun writing this. It turned out to be a bit harder than I expected, mainly due to all the corner cases like point being on one of the delimiters—like most programming, really. I wrote plenty of unit tests to be sure to handle these cases. It’s very little code now, but when I first had a working version, it was twice as big. Once I had it working, I could see lots of symmetry between the different cases that I could extract into shared code.

Also, I finally learned the condition-case error handling of Emacs. And being able to pass functions as arguments is just great, coming from my mostly-Java day job.

Try it out if it sounds useful to you, and let me know what you think.

Slightly edited 2010-05-16.