Thursday, January 1, 2009

Object initialization

Programming in Java, I find it troublesome to initialize the newly created objects. For instance, there are JButton(name) and JButton(Action) constructors; how do I want to initialize both? Or, in order to initialize a JList:
JList jl = new JList(items);
 jl.setLayoutOrientation(JList.HORIZONTAL_WRAP);
 jl.setVisibleRowCount(-1);

 jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

 jl.setDragEnabled(true);
 jl.setDropMode(DropMode.ON_OR_INSERT);
 jl.setTransferHandler(new TransferHandler() {
 ...

Because Java has no Delphi with construction, we cannot write simply say

JList jl = new JList(items);
with jl {
 setLayoutOrientation(JList.HORIZONTAL_WRAP);
 setVisibleRowCount(-1);

 setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

 setDragEnabled(true);
 setDropMode(DropMode.ON_OR_INSERT);
 setTransferHandler(new TransferHandler() {
 


I, therefore, avoid redundancy using double-brace initialization
JList jl = new JList(items) {{
 setLayoutOrientation(JList.HORIZONTAL_WRAP);
 setVisibleRowCount(-1);

 setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

 setDragEnabled(true);
 setDropMode(DropMode.ON_OR_INSERT);
 setTransferHandler(new TransferHandler() {

It is a nice syntactic trick. At first glance it seems ok and encouraged by both java experts, who recommend a "Helper" class for every tiny problem and Java workflow itself (recall that every single callback and event handler requires a new class). But, I suspect that there is an implementation overhead: creating a class for the sake of initializing just a couple of fields results in many classes. Their loading takes time and storage takes space, which also implies additional caching penalty.

I have invented alternative way: the language must support properties, which must/may be initialized by the user:
jl = new JList(
 items = items,
 layout = HORIZONTAL_WRAP,
 rowcount = -1,
 selectionMode = SINGLE_SELECTION,
 dragEnabled = true,
 dropMode = ON_OR_INSERT,
 transferHandler = new TransferHandler() {...
);

:))

I wish Java had the Delphi with construction. But named arguments could also be very helpful, especially in constructors. They enable optional parameters and make the code more self-descriptive.

There is a final-problem with object initializers in Java.

No comments: