# A repeated string formatting operation

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

• I think as this question currently stands it risks falling under the category of "stub or hypothetical code", which is off topic for this site. You should probably modify your snippets to something that represents a real implementation with some identifiable purpose, with meaningful names, etc. Jul 2, 2015 at 14:22
• @Ben Aaronson, Question updated as requested, and thanks for the advice.
– GJ.
Jul 2, 2015 at 14:54

## 1 Answer

Sure, your method is better. It's a pretty straightforward example of some fundamental programming and design concepts:

• You spotted repetition. The same information is being stated multiple times. In this case, the information is how to perform a particular operation for formatting a string. Generally, you should not repeat yourself.
• This clued you in to an abstraction: the implementation of this formatting operation can be abstracted out behind a meaningful name
• With this knowledge you abstracted out the operation by applying an extract method refactoring.
• As a result, you now have code which is:
• More readable, since the methods are simpler, and the name of the formatting method explains exactly what its purpose is.
• More maintainable, since now any change to this formatting operation just has one place to occur, rather than having to be made in all the places that it's repeated