The hardly known MessageFormat
I wonder how many people actually know about SQL code or log messages.
Edited: removed the SQL code generation. As noted in the comments, it's better to use PreparedStatement instead.
java.text.MessageFormat. I didn't until a few days ago, and it's a shame, in my opinion.
In Java 5.0, we were introduced with a new feature which was the new String.format method, with the complimentary PrintStream.printf method (classically used via the System.out member). This feature allowed us to go back to the old C days, and write things like String.format("The index is %d", idx) instead of the old, familiar System.out.print("The index is " + idx). Obviously, better uses for this method have been found.
However, the MessageFormat class provided this functionality, even if in a bit more complicated manner, years ago. Getting to know MessageFormat I found out that:
- It's faster For a simple format, such as "The index is X and the letter is Y" where X was some loop index and Y was the character achieved by
'a' + (X % 26),MessageFormat.formatworked about three times faster thanString.format. - It's bi-directional With a complimentary
MessageFormat.parsemethod, you could extract the same parameters you use for formatting from an already formatted text. - Optional choice formatting Inside the format pattern you can define conditions that would show different values relevant to the value passed. For example, you could show "no entries" if the value passed was 0, and "X entries" if the value passed was higher, by just writing
{0, choice, "0#no entries|0< {0} entries"}as a format pattern. Obviously, there's a class externalising this behaviour calledChoiceFormat.
Comments (8)