Handling Plurals and Singulars
Reference > Science > Technology > Beginner Programming TipsOkay, here's what I want to know: have you ever done a piece of code like the following?
Dim Seconds As Integer
Dim Minutes As Integer
If Minutes = 1 Then
MyString = MyString & Minutes & " minute"
Else
MyString = MyString & Minutes & " minutes"
End If
If Seconds = 1 Then
MyString = MyString & " and " & Seconds & "
second"
Else
MyString = MyString & " and " & Seconds & "
seconds"
End If
What does this piece of code do? It looks at the variable Seconds, and determines whether to use the singular form or the plural form of the word "second." Then it does the same with for the word "minutes."
So if Minutes = 1 and Seconds = 5, this code would produce the string: 1 minute and 5 seconds. If Minutes = 5 and Seconds = 1, it would produce the string: 5 minutes and 1 second.
The code works, but it's not very practical if you are going to be doing this kind of thing a lot!
Take a look at the following function.
PluralForm As String, Count As Integer) As
String
If Count = 1 Then
Pluralize = SingularForm
Else
Pluralize = PluralForm
End If
End Function
Here's how this works. You pass to the function both the singular and plural forms of the word you are dealing with, and an integer value indicating the count of objects.
Now let's take a look at how this works.
Dim Seconds As Integer
Dim Minutes As Integer
MyString = Minutes & " " & _
Pluralize("minute", "minutes", Minutes)
MyString = MyString & Seconds & " " & _
Minutes & Pluralize("second", "seconds",
Seconds)
Isn't that going to make life a whole lot easier for you if you have to evaluate a lot of singular/plural expressions?
Another Version
Another version of this function could be created which only required you to pass the Count variable, and then the function simply returns an 's' if the word is supposed to be plural, or nothing if the word is supposed to be singular. Here's how the function would look:
If Count = 1 Then
Pluralize = ""
Else
Pluralize = "s"
End If
End Function
Such a function would be used like this:
This second version of the function seems like it might be better, since it saves having to pass two extra variables. However, what seems to be true is not always so. Why is this second version of the function not as good as the first one?