Monday, January 22, 2007

Why XML is so important for Java

Lately, I thought about programming languages concepts I like.
One of those concepts would be a syntax for object initialization and creation, like c# 3.0 will have it.
Here's an example:

var r = new Rectangle {
P1 = new Point { X = 0, Y = 1 },
P2 = new Point { X = 2, Y = 3 }
};


Within the curly brackets the object initialization is described. One can assign values to all settable properties. With such a syntax one can create deep object graphs inline, without the need to provide constructors for all possible combination of initial values. (Ignoring that the example from above, which is taken from the C#3.0 spec, is a bad one. Rectangle and Point are typically implemented as immutable ValueObjects. So they should provide the respective constructors.)

Anyway, there are a lot of mutable types, which have to be created in the code. If you need to describe structural information, which has to be loaded and used at runtime, the Java folks typically use XML to describe those structures.
Take the spring configuration for example. The main thing about dependency injection is to create and wire up complex object graphs. Why shouldn't we describe them in Java?
Because of the imperative syntax:

With XML you can write:

<bean class="my.Example">
<property name="val1" value="Hello World!"/>
<property name="val2" value="Foo Bar"/>
<property name="ref1">
<bean class="my.Example2">
<property name="bla" value="dubidu"/>
</bean>
</property>
</bean>


In Java (without constructors) you have to write:

Example ex = new Example();
ex.setVal1("Hello World!");
ex.setVal2("Foo Bar");
Example2 ex2 = new Exmaple2();
ex2.setBla("dubidu");
ex.setRef1(ex2);


Although the imperative Java code above is not longer than the XML code, it doesn't reflect the structure of the created object graph. The XML code does!

If Java had a syntax for object graph creation and initialization we could write the following instead:

Example ex = new Example {
val1 = "Hello World!"
val2 = "Foo Bar"
ref1 = new Example2 {
bla = "dubidu"
}
}


This is IMHO not only the most readable version, but would also be better integrated into Java (as it would be Java). Think of tool support like code completion, static compiler checks, refactoring support, etc.