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

Vowels in a String are in Alphabetical Order

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

Problem

Task

Write an implementation that returns whether a String has vowels (English language) in alphabetical (A-Z) order or not.

Feedback

  • Is my vowels variable appropriate? Is there a better way to implement a vowel lookup?



  • If a candidate String has no vowels, the validator will return true - is that reasonable? From a logical perspective, the program isn't lying, but you could make the same argument if it returned false. Would it be better to return an exception - something like NoVowelsInCandidateException?



Implementation

public class VowelOrderValidator {
    private static final List vowels = new ArrayList<>(
            Arrays.asList('A', 'E', 'I', 'O', 'U', 'Y')
    );

    public static boolean areVowelsOrdered(final String candidate) {
        final char[] chars = candidate.toUpperCase().toCharArray();
        int lastVowelIndex = 0;
        for (final char c : chars) {
            final int lookupIndex = vowels.indexOf(c);
            if (-1 != lookupIndex) {
                if (lookupIndex < lastVowelIndex) {
                    return false;
                } else {
                    lastVowelIndex = lookupIndex;
                }
            }

        }

        return true;
    }
}

Solution


  • Since vowels is a constant for your program, the convention would be that its name is in all uppercase, like VOWELS.



-
Take great care when uppercasing Strings:

final char[] chars = candidate.toUpperCase().toCharArray();


Uppercasing a String depends on the locale. By not specifying a locale, you are relying on the default locale of the JVM, which may cause problems for Turkish users (for example). It would be better to specify the ROOT locale:

final char[] chars = candidate.toUpperCase(Locale.ROOT).toCharArray();


-
I'm not a big fan of inversing the conditions in an if:

if (-1 != lookupIndex) {


The following would be easier to read:

if (lookupIndex != -1) {


In fact, it would be even better to not check against -1 but test that the result is positive:

if (lookupIndex >= 0) {


It decouples the fact that indexOf returns -1 from what you really want to test, which is that the index was found.

  • I think returning true when there is no vowels is the least surprising result: when there are no vowels, then they all are in the right order. Throwing an exception would be a bad idea: no vowels in a String is not a real exceptional condition.

Code Snippets

final char[] chars = candidate.toUpperCase().toCharArray();
final char[] chars = candidate.toUpperCase(Locale.ROOT).toCharArray();
if (-1 != lookupIndex) {
if (lookupIndex != -1) {
if (lookupIndex >= 0) {

Context

StackExchange Code Review Q#119205, answer score: 7

Revisions (0)

No revisions yet.