Java – Should I use java.text.MessageFormat for localised messages without placeholders

javalocalizationmessageformat

We are localising the user-interface text for a web application that runs on Java 5, and have a dilemma about how we output messages that are defined in properties files – the kind used by java.util.Properties.

Some messages include a placeholder that will be filled using java.text.MessageFormat. For example:

search.summary = Your search for {0} found {1} items.

MessageFormat is annoying, because a single quote is a special character, despite being common in English text. You have to type two for a literal single quote:

warning.item = This item''s {0} is not valid.

However, three-quarters of the application's 1000 or so messages do not include a placeholder. This means that we can output them directly, avoiding MessageFormat, and leave the single quotes alone:

help.url = The web page's URL

Question: should we use MessageFormat for all messages, for consistent syntax, or avoid MessageFormat where we can, so most messages do not need escaping?

There are clearly pros and cons either way.

Note that the API documentation for MessageFormat acknowledges the problem and suggests a non-solution:

The rules for using quotes within
message format patterns unfortunately
have shown to be somewhat confusing.
In particular, it isn't always obvious
to localizers whether single quotes
need to be doubled or not. Make sure
to inform localizers about the rules,
and tell them (for example, by using
comments in resource bundle source
files) which strings will be processed
by MessageFormat.

Best Solution

Just write your own implementation of MessageFormat without this annoying feature. You may look at the code of SLF4J Logger.

They have their own version of message formatter which can be used as followed:

logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);

Empty placeholders could be used with default ordering and numbered for some localization cases where different languages do permutations of words or parts of sentences.