Pergunta

The following code is bug free. But, it fine so long as if (i == a.length - 1 || a[i] != a[i + 1]) condition maintains its order. Swapping the if conditions to if(a[i] != a[i + 1] || i == a.length - 1) would throw an exception. Is preventing an exception by short circuiting, an expectable coding standard Or is there some theory / design pattern warning against such coding practices ? If so please advise with links / materials.

 public static void eliminateDuplicate(int[] a) {
    if (a == null) {
        throw new NullPointerException();
    }
    List<Integer> list = new ArrayList<Integer>();

    for (int i = 0; i < a.length; i++) {
        if (i == a.length - 1 || a[i] != a[i + 1]) {
            System.out.println("now what : " + a[i]);
            list.add(i);
        }
    }
}
Foi útil?

Solução

It's a common practice to use short-circuit operator to avoid exceptions. And it is obviously standard.

JLS Section 15.24 - Conditional OR operator:

The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

  • ConditionalOrExpression:
    • ConditionalAndExpression
    • ConditionalOrExpression || ConditionalAndExpression

Given your case, it would be pretty more clear if you use Conditional && operator and change your condition to:

if (i < a.length - 1 && a[i] != a[i + 1])

The intention is more clear in this code on the first look. Frankly speaking I had to go through twice over your condition to figure out what is it doing.

Again not related to concrete question, I'll modify your for loop to use maximum index one less than you are using currently, to avoid the conditional operator entirely:

for (int i = 0; i < a.length - 1; i++) {
    if (a[i] != a[i + 1]) {
        System.out.println("now what : " + a[i]);
        list.add(i);
    }
}

Some Common Examples:

Some quite common examples where you would see the use of conditional operators to avoid exceptions are:

Overriding equals() method:

public boolean equals(Object obj) {
    return obj instanceof MyClass && ((MyClass)obj).num == this.num;
}

Handling null reference in some method invocation:

// Although there are better way to do this.
if (str != null && str.equals(str2)) {
    // some code
}

Avoiding division by zero:

if (x != 0 && 4/x > 1) {
    // some code
}

Contrary to this, all the above codes will throw exception at runtime, if you use Boolean Logical Operator, and the first expression evaluates to false.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top