JMU
Pluralization
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Review
A Solution that is Prone to Error
javaexamples/programmingpatterns/pluralization/Pluralization.java (Fragment: 1)
                if (n == 1) {
            result = "There is 1 poodle available for adoption.";
        } else {
            result = "There are " + n + " poodles available for adoption.";
        }
        
Review (cont.)
A Cumbersome Solution
javaexamples/programmingpatterns/pluralization/Pluralization.java (Fragment: 2)
                result = "There";

        if (n == 1) result += " is";
        else        result += " are";
        
        result += " " + n + " poodle";
        
        if (n > 1) result += "s";
        
        result += " available for adoption.";
        
Thinking About the Problem
The Pattern
The Pattern (cont.)
The General Purpose Method
javaexamples/programmingpatterns/pluralization/Pluralize.java (Fragment: form)
            /**
     * A method used to choose between two forms.
     *
     * @param n         The number of items
     * @param singular  The singular form
     * @param plural    The plural form
     * @return          The singular or plural form
     */
    public static String form(int n, String singular, String plural) {
        if (n > 1) return plural;
        else       return singular;
    }
        
Example
Specific Words
javaexamples/programmingpatterns/pluralization/Pluralize.java (Fragment: is)
            /**
     * A method used to get the singular or plural form
     * of the word "is".
     *
     * @param n  The number of items
     * @return   "is" or "are"
     */
    public static String is(int n) {
        return form(n, "is", "are");
    }
        
Example
Regular Nouns
javaexamples/programmingpatterns/pluralization/Pluralize.java (Fragment: regular)
            /**
     * A method used to get the singular or plural
     * form of a regular noun.
     *
     * @param n  The number of items
     * @param noun The regular noun
     * @return   "s" or ""
     */
    public static String regular(int n, String noun) {
        return noun + form(n, "", "s");
    }
        
Example (cont.)
Using the Pattern
javaexamples/programmingpatterns/pluralization/Pluralization.java (Fragment: 3)
                result = "There " + Pluralize.is(n) + " "
            + n + " " + Pluralize.regular(n, "poodle")
            + " available for adoption.";
        
javaexamples/programmingpatterns/pluralization/Pluralization.java (Fragment: 4)
                result = "There " + Pluralize.is(n) + " "
            + n + " " + Pluralize.form(n, "mouse", "mice")
            + " available for adoption.";