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?
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.