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

Returning a string representation of the number of albums and songs available

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

Problem

What this method should do is return a String that displays how many albums and songs there are. This method is a private method of my Artist class which has a method called albumCount() and songCount(). The whole class probably needs an improvement but I will try that later. First I'd like this single method to be improved if possible.

public String toAlbumSongCount() {
    StringBuilder builder = new StringBuilder();

    final int albumCount = albumCount();
    final int songCount = songCount();

    builder.append( albumCount );
    //Append albums instead of album if albumCount is greater than 1
    builder.append( (albumCount > 1) ? " albums" : " album" );
    builder.append( "," ); //Move this to the line above?
    builder.append( songCount );
    //Append songs instead of song if songCount is greater than 1
    builder.append( (songCount > 1 ) ? " songs" : " song" );

    return builder.toString();
}


I used the StringBuilder class because I heard a dozen of times that it will improve performance when concatenating Strings.
I wasn't sure about those two lines :

builder.append( (albumCount > 1) ? " albums" : " album" );
builder.append( (songCount > 1 ) ? " songs" : " song" );


Are they good enough with the comments above them?

I appreciate any help even if it means completely rewriting this method.

Solution

Text manipulation like that is always a pain. I like to extract functions for things like this, though.

private static final String simplePlural (int count, String noun) {
    if (count == 1) {
        return "1 " + noun;
    }
    return count + " " + noun + "s";
}


With that function, your code becomes:

public String toAlbumSongCount() {
    return simplePlural(albumCount(), "album") 
       + ", " + simplePlural(songCount(), "song");
}


I know there's no StringBuilder in there, but the performance benefit for something that's seldom used, will be negligible, and this is more readable.

Note that the code above adds a space after the comma, which your code is missing.

Code Snippets

private static final String simplePlural (int count, String noun) {
    if (count == 1) {
        return "1 " + noun;
    }
    return count + " " + noun + "s";
}
public String toAlbumSongCount() {
    return simplePlural(albumCount(), "album") 
       + ", " + simplePlural(songCount(), "song");
}

Context

StackExchange Code Review Q#93635, answer score: 5

Revisions (0)

No revisions yet.