As I'm reading the Java code of some other people, I found him using an approach of assigning a format string to a variable and using the variable for String.format
in the code:
private final static String URI_SUFFIX_FORMAT = "view/%s";
@Inject
private UriBuilder uriBuilder;
public void buildUriForMusic(String dir)
{
...
String ret = uriBuilder.buildContentUri(dir, String.format(URI_SUFFIX_FORMAT, "music"));
...
}
public void buildUriForBook(String dir)
{
...
String ret = uriBuilder.buildContentUri(dir, String.format(URI_SUFFIX_FORMAT, "book"));
...
}
I don't like the use of URI_SUFFIX_FORMAT
in the above code because I cannot tell what that String.format
is trying to compose and if the number of String
s passed in is correct or not.
I prefer to do this instead:
private String formatUriWithSuffix(String dir, String service)
{
return uriBuilder.buildContentUri(dir, String.format("view/%s", service));
}
public void buildUriForMusic(String dir)
{
...
String ret = formatUriWithSuffix(dir, "music");
...
}
public void buildUriForBook(String dir)
{
...
String ret = formatUriWithSuffix(dir, "book");
...
}
What do you think? Which one is better, for what reasons? Do you have a better approach?