views:

318

answers:

6

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?

+1  A: 

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

Steve
A: 

Personally, I would stick with the concatenation way, but it's just a matter of preference. Some people think it's cleaner to write a string with variables as one string, and then pass the params as a list after the string. The more variables you have in the string, the more sense using MessageFormat makes, but you only have one, so it's not a big difference.

Jez
+1  A: 

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
Kevin
+4  A: 

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

According to your teacher your should.

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

While in the sample you provided it doesn't makes 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.

OscarRyz
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.
Sam Barnum
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.
OscarRyz
Although everyone had the same answer, I'll tag this one since it also gives a simple example for i18n.
Ramon Marco Navarro
A: 

One advantage that I see in using MessageFormat is that when you decide to externalize your strings, it would be much easier to build the message and also, it makes more sense to see "Username '{0}' not found!" in your resource file as one string accessed by only one ID.

bruno conde
A: 

Of course if you don't need internationalization, it is overhead, but basically the code as the teach wants it is more "internationalizable" (although not actually internationalized as the string is still hard coded).

Since this is a teaching situation, though he may be doing it just to show you how to use those classes rather than as the best way to program for this specific example.

In terms of the best way to program, if internationalization is a requirement, then you need to code for it, if not then don't. I just adds overhead and time (to write the code) for no reason.

Pace the other answers, the importance of MessageFormat for internationalizion is not just that it makes it easier to make an external file. In other languages the location of the parameter may be different in the sentence structure of the messages, so using MessageFormat allows you to change that per language, something that string concatenation would not.

Yishai