开发者

Benefits of MessageFormat in Java

开发者 https://www.devze.com 2022-12-08 07:04 出处:网络
In a certain Java class for a Struts2 web application, I have this line of code: try { user = findByUsername(username);

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.for开发者_如何学Gomat(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?


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.


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


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消