Thoughts on the Craft of Programming: Abstraction, Refactoring, and How Changes Introduce Bugs - Cleaning Code
(Page 3 of 6 )
Cleaning Up the Switch Statement That fixed the bug, but the switch statement looks a bit silly now, and would look even sillier if I had stripped it to its bare essentials by also removing the default case and the preceding continue (which is made redundant by the removal of the default) -- even though, if compiled using a branch table, the switch statement would be quite efficient. In any case, I tend to look askance at continue statements3. Figure 3 shows how we can replace the switch with a more straightforward if statement.
Figure 3: Cleaning Up the switch Statement Code
Replace the Ugly if That's reasonable and not too inefficient, but the if statement looks a bit ugly. We now need to switch our focus from the scientific -- getting the code correct -- to the artistic -- making the code good. Let's replace the ugly statement with a nicer test, using the C run-time library: a tiny4 example of component-based development, with the library acting as a component.
Usually, strchr is employed to search for a given character in an arbitrary string; here we invert that to search for an arbitrary character in a given string. Its specification is "strchr searches a string for the first occurrence of a character; if the character is found in the string, a pointer to the first occurrence is returned, otherwise a null pointer is returned." We use it in the logically equivalent way: The character occurs in the string if and only if strchr returns a nonzero value. On x86 CPUs with a decent compiler this version will also be a little faster. Notice that the total amount of text (Figure 4) is now substantially reduced, which also contributes to the code's being easier to read and understand.
Figure 4: Replace the Ugly if Code
Making a Simple Enhancement
As shown in Figure 4, we might notice that only lowercase letters are counted as vowels. Let's improve the code so that it will accept uppercase vowels as well. Given the improvements we've made thus far, this is now very easy and safe to do, since the only change needed is to extend a static array. Note that if we had made an equivalent change to Version 3, the if statement would have become really ugly and significantly inefficient. The change shown in Figure 5 is by no means the only way to implement this enhancement; arguably it would be just as good, for example, to initialize the vowels array with only the uppercase vowels, and pass toupper(*s) to strchr.
Figure 5: Enhancement to Accept Uppercase Vowels
Next: Vowels >>
More Development Cycles Articles
More By The Rational Edge