Java Tips: MessageFormat

Writing a working code is not enough. There is so wide spectrum from where we can distinguish good programmer and a bad one. This is one example of it.

Suppose we need to write a String that concatenate several predefined substrings with several variables. What do we do? Obviously, the most natural thing is to write:

String c = "The book with title " + title + " is sold with price "
              + price + " to " + buyername;

Nothing wrong with the code but obviously if the sentence build many times, you already know that it’s not that efficient. The use of StringBuffer or StringBuilder in Java 5 can make it much better.

String c = new StringBuilder("The book with title ").append(title)
                    .append(" is sold with price ").append(price)
                    .append(" to ").append(buyername);

Great! But not for future development. The code looks cryptic and hard to be changed. The use of MessageFormat is the best solution for such problem (which unfortunately, also the most inefficient).

String result = MessageFormat.format(
     "The book with title {0} is sold with price {1} to {2}",
      new Object[] {title, price, buyername});

This is even better since we can customize the format of the price, for example:

String result = MessageFormat.format(
     "The book with title {0} is sold with price {1,number,currency} to {2}",
      new Object[] {title, price, buyername});

Leave a Reply

Your email address will not be published. Required fields are marked *