Benefits of MessageFormat in Java

14,224

Solution 1

Should I change the line of code or stick with the current?

According to your teacher your should.

Perhaps he wants you to learn different approaches for the same thing.

While in the sample you provided it doesn't make much sense, it would be useful when using other types of messages or for i18n

Think about this:

String message = ResourceBundle.getBundle("messages").getString("user.notfound");

throw new UsernameNotFoundException(MessageFormat.format( message , new Object[] {username}));

You could have a messages_en.properties file and a messages_es.properties

The first with the string:

user.notfound=Username '{0}' not found!

And the second with:

user.notfound=¡Usuario '{0}' no encontrado!

Then it would make sense.

Another use of the MessageFormat is described in the doc

 MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
 double[] filelimits = {0,1,2};
 String[] filepart = {"no files","one file","{0,number} files"};
 ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
 form.setFormatByArgumentIndex(0, fileform);

 int fileCount = 1273;
 String diskName = "MyDisk";
 Object[] testArgs = {new Long(fileCount), diskName};

 System.out.println(form.format(testArgs));

The output with different values for fileCount:

 The disk "MyDisk" contains no files.
 The disk "MyDisk" contains one file.
 The disk "MyDisk" contains 1,273 files.

So perhaps your teacher is letting you know the possibilities you have.

Solution 2

Teachers way allows for easier localisation as you can extract a single string rather than several little bits.

Solution 3

But I don't see the point of using MessageFormat in this situation

In that specific situation it doesn't buy you much. In general, using MessageFormat allows you to externalize those messages in a file. This allows you to:

  • localize the messages by language
  • edit the messages outside without modifying source code
Share:
14,224
Ramon Marco L. Navarro
Author by

Ramon Marco L. Navarro

I am me.

Updated on June 06, 2022

Comments

  • Ramon Marco L. Navarro
    Ramon Marco L. Navarro about 2 years

    In a certain Java class for a Struts2 web application, I have this line of code:

    try {
        user = findByUsername(username);
    } catch (NoResultException e) {
        throw new UsernameNotFoundException("Username '" + username + "' not found!");
    }
    

    My teacher wants me to change the throw statement into something like this:

    static final String ex = "Username '{0}' not found!" ;
    // ...
    throw new UsernameNotFoundException(MessageFormat.format(ex, new Object[] {username}));
    

    But I don't see the point of using MessageFormat in this situation. What makes this better than simple string concatenation? As the JDK API for MessageFormat says:

    MessageFormat provides a means to produce concatenated messages in language-neutral way. Use this to construct messages displayed for end users.

    I doubt that the end users would see this exception since it would only be displayed by the application logs anyway and I have a custom error page for the web application.

    Should I change the line of code or stick with the current?

  • eCommerce Guru
    eCommerce Guru over 14 years
    Not sure how much sense it makes to localize exception messages. Does the user ever see it? You can leave exceptions non-localized, and in the code that handles the exceptions, generate a nice localized message for the user to see.
  • OscarRyz
    OscarRyz over 14 years
    Quite frankly me neither, but BEA, Oracle and much other products do it. But I HATE IT, because I never can find useful information when looking at the localized error message ( so I always switch to english when possible ). Yet, this is useful to show the flexibility of the class, not because ALL the error messages should be done that way.
  • Ramon Marco L. Navarro
    Ramon Marco L. Navarro over 14 years
    Although everyone had the same answer, I'll tag this one since it also gives a simple example for i18n.