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
    order++;
}

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);
            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?

Bash history essentials

I’ve been using the Bash history since a long time, but in a rather limited way. I’d use the “history” command, !<num> to execute command again, !* to get all parameters of the last command, and Ctrl-r to match previous commands.

This article by symkat showed me a lot more interesting history features.

Here’s my personal list of what a productive developer needs to know about Bash history:

  • history: Show the history in case you get lost.
  • !<num>: Execute line again, where is the number shown by history.
  • Ctrl-p: Browse the history backwards. Also on cursor-up, but doesn’t make you leave touch typing position.
  • Ctrl-r: Search backwards. Invaluable. Matches can anchor anywhere. Pressing it repeatedly shows older matches.
  • !$: Substitutes for the last word of the previous line. Very useful for doing something else with the same thing. For example, you might first say ls -R very/long/path, then du !$ to show the directory’s size.
  • Esc-. or Alt-. (that’s Alt-PERIOD): Like !$, but Bash inserts the word into your current line right away, so you can check or modify it.

Also, setting the HISTCONTROL environment variable to “Ignoreboth” to ignore duplicate history entries and commands starting with a space is a must.

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”

Mocking LWP::UserAgent with POST redirection

To test the ubiquitous (and awesome) LWP::UserAgent module, I use Test::Mock::LWP. It works as advertised, with minimal code. However, I still found myself writing a little plumbing. Here are two code snippets that I use when using Test::Mock::LWP.

First, a way of mocking code using LWP::UserAgent’s requests_redirectable array, as in


sub _new_agent {
    my $agent = LWP::UserAgent->new;
    push @{$agent->requests_redirectable}, 'POST';
    return $agent;
} 

This won’t work with vanilla Test::Mock::LWP, as requests_redirectable is not a method and therefore cannot be mocked – a small flaw in UserAgent’s API. To circumvent the problem, mock your own UserAgent creation sub (you did encapsulate that, didn’t you):


use Test::MockObject;

# In addition to Test::Mock::LWP, we also need to mock our own
# wrapper for LWP::UserAgent->new, as it needs UserAgent's
# requests_redirectable array and the mock doesn't have that.
Test::MockObject->new()
  ->fake_module('My::Foo',
                '_new_agent' => sub { return LWP::UserAgent->new; }
               );

Second, just a tiny sub to make things nicer, IMHO: it provides a clean abstraction to get the latest requested URL. It’s useful if that’s all you want to test. This makes tests nicer to read and isolates them from the mocking module. It also encapsulates the magic index we need to get the requested URL from the request header array. The index is 2 here, this works for code making requests using HTTP::Request::Common. It’s probably different if you use HTTP::Request directly, but the test runner’s expected/actual output will quickly show you where the URL hides.

sub latest_requested_url {
    return scalar $Mock_request->new_args()->[2];
}

A better less, playing nice with git

On the command line, I used to look at files with less or cat, depending on how long I expected the file to be. Of course I would constantly guess wrong, either blocking my screen with less showing only a handful of lines and making me press “q” needlessly, or having cat’s output scrolling past.

But recently I discovered how to make less do everything I want. -F or --quit-if-one-screen is self-explanatory and avoids needless “q”-presses, and -X or --no-init makes less not clear the screen when invoked. With these two options, less behaves like cat when it makes sense.

I enjoyed my new enhanced less-ing… until I invoked git diff. It looked like this, the line endings seemingly garbled:

ESC[1mdeleted file mode 100644ESC[m
ESC[1mindex bc7f954..0000000ESC[m
ESC[1m--- a/src/test/org/expasy/cvrelational/keywords/KeywordRoundtripTest.javaESC[m
ESC[1m+++ /dev/nullESC[m

Oops! The solution, thanks to those guys, is to add -R or --RAW-CONTROL-CHARS. I had git color its output automatically (git config --global color.ui auto), and less was choking on the control characters git added to its output.

Now, export LESS="-F -X -R" works like a charm.