Posts Tagged ‘java’

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?

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.


Elsewhere: Java generics


This one is basically a write-up of a collection of links about Java generics. Yes, I know, it doesn’t get any more boring. Every Java developer knows this by now, and the cool kids have moved to Scala and Clojure. (I’m working on it, too.) But at work I kept seeing that while the idea is simple, using generics in practice in a useful way is not easy for beginners. So I started tidying up a few bits and pieces I had written for colleagues and had that in my drafts for over a year now, and as I think it’s at least a collection of the best references about generics, here it is.

Let me get it out of the way first: every Java developer should know the Generics in the Java programming language tutorial by Gilad Bracha. Definitely study this first, and that might be enough for most people.

If you’re like me and need another round of explanations and examples to fully get the corner cases, Brian Goetz’s two articles on developerworks are great.

The second article addresses the question

Because the language supports both upper- and lower-bounded wildcards, how do we know which one to use, and when?

Goetz answers

There’s a simple rule, called the get-put principle, which tells us which kind of wildcard to use. The get-put principle, as stated in Naftalin and Wadler’s fine book on generics, Java Generics and Collections (see Resources), says: “Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you do both.”

Read the article if that concerns you at all, it’s very useful. I particularly like his clear explanation and example for the less often used lower-bounded wildcard:
public static <T extends Comparable<? super T>> void sort(List<T>list) { ... }

Goetz explains the idea behind the wildcard in the example like this:

[…] rather than restricting the domain of sort() to lists whose elements are comparable to themselves, we can go further — we can sort lists of elements that know how to compare themselves to their supertypes, too.

Alternatively we could say the Comparator must be able to compare at least T – if it can compare more, i.e., more generic types, we’ll take that as an added bonus.

Finally, let’s be balanced and mention the big shortcoming of Java generics: the type erasure, i.e., that the generic types are erased by the compiler and are not available at runtime. So, if you have a List and cast it to an untyped List, you can then insert any old Object into it. Mike Stone explains this in detail.

Java is pass-by-value


Does the Java parameter passing follow pass-by-value or pass-by-reference semantics? For primitives, it must obviously be by value, since we don’t have any references. For objects, you can find a large number of discussions on the net, some quite heated. Today it came up once again on Hacker News, as a link to Scott Stanchfield’s Java is Pass-by-Value, Dammit!.

The answer is absolutely clear, as Scott correctly points out. Java passes the object references by value. This is not the same thing as passing the references directly, and it’s not the same thing as passing the objects as data, i.e., as deep copies. The code sample below shows why the distinction is important.

I only write this to make one more small contribution to the enlightenment of Java programmers, and to highlight a piece of code from the comments of the HN discussion because it’s probably the simplest way of clearly demonstrating the truth of Scott’s article.

public class Test
    public static void main(String[] args)
        Object x = null;
        makeString (x);
        System.out.println (x);

    static void makeString (Object y)
        y = "This is a string";

If you execute this, you see that the reference to x cannot have been passed to makeObject.

Testing Wicket ListViews using IVisitor


The standard solution for unit testing Wicket apps is WicketTester. It works fine, but doesn’t offer much for testing ListViews. The assertListView method lets you test the contents of the ListView, but not the UI.

You can always extract the ListView rows into a Panel, of course. But when you don’t want to do that for whatever reason, it’s simple to side-step WicketTester and do the necessary tests yourself, especially since rows that are not in a panel of their own should be pretty simple.

An approach that works well for me is visiting the ListItems using MarkupContainer.visitChildren() and then accessing their components via Component.get(). To focus on the essential part, I’m using a method listView() in my example that gets the ListView from the rendered page. Once we have it, we visit its items.

listView().visitChildren(ListItem.class, new IVisitor<ListItem>()
	public Object component(ListItem item)
		Component uri = item.get("uri");
		// etc.
		// If testing one row is enough, we can stop here.
		return IVisitor.STOP_TRAVERSAL;

Once you see it, it’s trivial. WicketTester’s assertComponent() isn’t magic, you can do the same in three lines: get the Component via its path, assert it’s actually present, and assert it’s the right type.

If you want to do further tests on the component’s internals, I find it practical to expose those through package-scoped methods, provided your tests are in the same package than your app.

Finally, something that bit me once: how ListItems work with the list model. Say we have this (just a rough sketch):

class Foo
	List bars;
	List<Bar> getBars() { return bars; }

// On some page, the model is a CompoundPropertyModel&lt;Foo&gt;.
add(new ListView<Bar>("bars")
	protected void populateItem(final ListItem<Bar> item)
		item.add(new WebMarkupContainer("id"));

If you get hold of the WebMarkupContainer(“id”), for instance using an IVisitor like I showed above, and you call getDefaultModelObject() on it, what do you get? One might expect a Bar; after all, it’s a ListView<Bar>. Not so – you get a Foo.

ListViews work on the original List instead of a copy. Each ListItem is backed by a ListItemModel, which knows the index of the element it represents, but has no model itself. When the model is looked up, the normal Wicket model chaining happens, so we get to the CompoundPropertyModel. The ListView code of course knows about this and uses the ListItemModel’s index to get the right Bar from the list. But getDefaultModelObject() doesn’t know about this and simply returns the Foo.

If you are in that situation, explicitly ask for the ListItemModel:

((ListItemModel) component.getDefaultModel()).getObject()

should give you a Bar. Of course, if you visit the ListItem itself like in the example above instead of a nested component, you can just call getObject() on it and it does the right thing.