From object to XML

JAXB (Java Architecture for XML Binding) provides an easy way of converting Java objects to XML. In the JAXB jargon, this is know as marshalling, where unmarshalling means the opposite action of extracting a Java object from an XML.

As a first example, let's see how to create an XML fragment like this:
<user id="42" rating="4.2">Bill</user>
from a Java class named User that has the user name, id, and rating as data member.

Even if this looks like a pretty simple job, still there are a couple of points that it could be interesting to pay attention to. Large part of the JAXB job is done by annotations, with the result that the code looks quite simple to understand at first sight, once you know what it is going on.

In this case, I want my class User to have a couple of annotations, one to state that it represents a root XML element, and the second one to let JAXB know that I want to put an annotation to the data fields, and not to their getters, to specify their XML role.

The result is something like this:
@XmlRootElement // 1
@XmlAccessorType(XmlAccessType.FIELD) // 2
public class User {
    @XmlValue
    private String name;
    @XmlAttribute
    private int id;
    @XmlAttribute
    private float rating;

    // getters and setters follow ...
}
1. This class is the root element for my XML
2. If you don't explicitly say that the accessor type should be found in the field definition, JAXB gets confused. If you comment this line out, you get an IllegalAnnotationsException, and a message saying that "Class has two properties of the same name".

Once you have defined your JAXB annotated class, it is just a matter of creating an object, and marshalling:
public String obj2xml(User user) {  
    try {
        JAXBContext ctx = JAXBContext.newInstance(User.class); // 1
        Marshaller marshaller = ctx.createMarshaller(); // 2
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // 3

        StringWriter sw = new StringWriter();
        marshaller.marshal(user, sw); // 4
        return sw.toString();
    }
    catch (JAXBException e) { // 5
        e.printStackTrace();
        return "<bad />";
    }
}
1. Create a JAXB context that knows about the User class.
2. Then from the context we get a marshaller.
3. Here I want to generate just an XML fragment, if I want to generate a full XML document, I would remove this line, and the generated XML would have this header:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4. Ask the marshaller to send its output to a StringWriter, from which the resulting XML could be extracted as a String.
5. In case of anything goes wrong, give an alarming feedback to the user (not a very polite thing to do, but here it will suffices) but still return a valid XML.

The full Java source code for the User class and a Main class using it are on github.

Go to the full post

Three solutions to the loop problem

The lack of a block scope in JavaScript leads to what is often called The Infamous Loop Problem, where we try to use the (supposed) cycle variable in a for loop to set a callback function.

Conceptually, the solution is quite easy. The trouble is caused by the loop variable, that actually does not have a local scope, so we provide to it a local scope. In JavaScript we have only function scope, so a function would help us to find a way out.

The question is, which function? Whichever it is better for you in your context, I'd say. Let's see the three answers that I guess are more natural.

In the previous post I have written a buggy piece of code that was storing a few functions when looping on an array, an then, in another for loop, it called those functions. Now I modify it to let it work as I expected, following three different approaches.

Closure in loop

This is the most idiomatic solution using "pure" JavaScript. We wrap the code in the for loop around a closure, designed just to provide a local scope for the loop variable.
function doSomething(msg) {
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ];
var buffer = [];

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = (function(j) { // 1
        return function() { // 2
            doSomething(messages[j]);
        }
    })(i); // 3
}

// ...

for(var k = 0; k < buffer.length; ++k) {
    buffer[k]();
}
1. We put in buffer the function returned by a closure, here defined, that take as input a parameter, named j, that is assigned a value defined in (3).
2. The function returned by the closure is almost the same function we defined in the original code. The difference is that I don't use anymore the loop variable, but the closure parameter.
3. This is the core of the solution. I assigned to the closure parameter the loop variable, in this way the closure captures its current value, that now has a local scope, as required.

After a while, I guess this would look as the most natural approach, but if your JavaScript mileage is low, you could be find it a bit overwhelming. In this case, maybe you could be more at ease with the following variation.

Closure in the function

The idea is to move the closure from the for loop to the recipient function. I refactor the code above, rewriting the for loop and doSomething(), renamed doSomethingElse() for the sake of clarity.
function doSomethingElse(index) {
    return function() { // 1
        console.log(messages[index]);
    }
}

// ...

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = doSomethingElse(i); // 2
}

// ...
1. The closure has been moved here. Notice that this function does not run any code, but returns a function.
2. Just a simple assignment!

This code is so much readable, but I am losing the connection between the loop (2) and the reason why I need a closure in (1). Someone who reads just doSomethingElse() would probably wonder why it returns a closure instead of doing directly its job.

jQuery.each()

If we use the jQuery library, we can get the advantages of both the previous solutions using the each() method.

We use the original doSomething() function, and we don't need a closure in the for loop, jQuery.each() is a function, so it provides its own scope.
$.each(messages, function(index, value) { // 1
    buffer[index] = function() { // 2
        doSomething(value);
    }
});
1. For each element in the messages array, we call a function where the first parameter is the current index, and value the message element currently accessed.
2. There's no need of a closure, we simply assign to the buffer element a function that calls doSomething(). The capturing of local values is performed by jQuery.each().

Go to the full post

The JavaScript infamous loop problem

There is no block scope in JavaScript. Once you get used to this truth, the loop issue stops to be mystery, and you can say goodbye to a bunch of quirky behaviors in your code.

The for loop is a typical construct where many programmers get surprised by JavaScript. So I decided to write this post to make the issue as clear as I can. In the next post I present a few alternative solutions.

Simple loop through an array

Let's start looking at a plain for loop that won't give any trouble at all. I have an array of mixed objects, I want to call for each of them a function that does something not relevant here:
function doSomething(msg) { // 1
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ]; // 2

for(var i = 0; i < messages.length; ++i) { // 3
    doSomething(messages[i]); // 4
}
1. I don't care much of what this function actually does, logging the parameter is more than enough.
2. This is the array I want to loop through.
3. A local variable, i, is declared and used as temporary location for the current element in the array.
4. The function is called for each element in the array.

As I said, this way to walking through an array works fine. Still, we should be aware of the fact that the supposed loop variable is not actually limited to that scope, but it is available all over the function scope in which the for loop is placed.

This doesn't work

Let's think to something a bit more complicated. Say that I don't want to call immediately the other function, I want to create an array of function, so that I can call them later, after I do some other task.

I could (wrongly) think to refactor the previous piece of code in this way:
function doSomething(msg) {
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ];
var buffer = []; // 1

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = function() { // 2
        doSomething(messages[i]);
    }
}

// ...

for(var j = 0; j < buffer.length; ++j) {
    buffer[j](); // 3
}
1. Temporary place where storing the functions to be called in a second time.
2. For each element in the message array, I create an unnamed function that calls doSomething().
3. And after a while I call all the functions stored in the buffer.

At a first sight, it looks like we should have the same result of the first example. But here we get just a desolating list of "undefined".

What happened here? The problem is that the loop variable is not actually such. So, when in (3) we call doSomething() through the buffer, the index is the current value (actually, the length of the message array) and not its value when in (2) we assigned the function to the buffer.

What we need to do is to capture the current value of the loop variable in (2) so that would be used in (3). We can achieve this result in a couple of different ways, as we'll see soon.

Go to the full post

Adding a DOM element

If you have to modify an existing DOM document in the fly by adding a HTML fragment, you can use the jQuery appendTo() method, that would simplify your job. Being jQuery smart enough to create a jQuery object from a HTML literal fragment, we can even operate on it before appending it.

To add a bottom line to an HTML page, I could write:
var fragment = $('<p><i>Bottom line</i></p>'); // 1
fragment.find('i').attr('class', 'z'); // 2
fragment.appendTo('body'); // 3
1. I create a P element containing an I element, containing some text.
2. Before actually adding it to my document, I can modify it. Here I get the I element and add to it an attribute, class='z'.
3. Finally, I add my fragment at the end of the BODY element.

There is no need of writing this code on three lines, I can squeeze it on just one, but I have to be careful:
$('<p><i>Bottom line</i></p>').find('i').attr('class', 'k').end().appendTo('body');
I need to call end() before appendTo(), otherwise I put to the document only the element returned by find(), and the paragraph would be lost.

Go to the full post