Wednesday, April 22, 2009

String interpolations in different languages

I am learning Groovy and refreshing my Python skills as well. While working on some examples, I realized that the operation of concatenating string to produce a larger string is a very frequently used operation. Very often parts of the string we are creating are already held in variables. A crude way of creating the larger string, is to simply concatenate everything as shown in this simple toString() method of the Person object.


public class Person {
//showing only relevant code
public String toString() {
return "Name: " + name + " salary: " + salary + " address: " + address;
}
}


However, this is not very readable. A better way is to use either string interpolation or templating. Java gives us a couple of ways to do templating.

We can either write the toString() method like this to become much more readable:


public String toString() {
return String.format("name: %s salary: %d address: %s", name, salary, address);
}


Or we can use the MessageFormat class:

return MessageFormat.format("name: {0} salary: {1} address: {2}", name, salary, address);


I personally think the last option is more readable. Moving to Python, it also gives us ways to do templating:


return "name: %s salary: %d address: %s" % (name, salary, address));


There is yet another way:

print "name: %(name)s salary: %(salary)d address: %(address)s" % locals()


Notice that both, Java and Python, support templating but not interpolation. Groovy on the other hand supports interpolation which is far more elegant and concise.


public class Person {
//showing only relevant parts of the code
public String toString() {
return """name: ${name} salary: ${salary} address: ${address}"""
}
}

No comments: