29 Jan 2009

Fomatting messages

I always found formatting Strings was painful in Java. Especially since I learn Ruby where you can do:
some = 'foobar'
my_string = "Here are #{some} value"

In Java, a basic example would be:
String searchPolygon = "POLYGON((" + lowerLeft + ", " + 
lowerRight + ", " + upperRight + ", "
+ upperLeft + ", " + lowerLeft + "))";

If you have too many parameters or you are looking for more efficiency, you can do something like (you can use StringBuffer instead of StringBuilder see javadoc):
StringBuilder searchPolygon = new StringBuilder();
searchPolygon.append("POLYGON((");
searchPolygon.append(lowerLeft);
searchPolygon.append(", ");
searchPolygon.append(lowerRight);
searchPolygon.append(", ");
searchPolygon.append(upperRight);
searchPolygon.append(", ");
searchPolygon.append(upperLeft);
searchPolygon.append(", ");
searchPolygon.append(lowerLeft);
searchPolygon.append("))");
searchPolygon.toString();

But still, it's ugly :(


Or you can use MessageFormat wich make the code more much readable in my opinion ;)

MessageFormat polygonFormatter =
new MessageFormat("POLYGON(({0}, {1}, {2}, {3}, {4}))");
Object[] values = new Object[] {
lowerLeft, lowerRight, upperRight, upperLeft, lowerLeft };
String searchPolygon = polygonFormatter.format(values);


It could have even be better if we could have use a map with key/value instead of indexes... but I didn't found anyting in the java language itself that does this :(

No comments: