HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

A repeated string formatting operation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formattingstringrepeatedoperation

Problem

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?

Solution

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

Context

StackExchange Code Review Q#95580, answer score: 10

Revisions (0)

No revisions yet.