This morning, a user asked a question about determining the equality of three values on ##java. The code he offered as a test was as follows, roughly:
boolean a=false, b=false, c=false; System.out.println(a == b == c);
Rather than determining if the three values are equivalent, this code checks to see if
a is the same as
b – with the result of
true – and then checks to see if this result is the same as
c – so it tries to see if
a == b is
false. It’s not, so the result of the expression is
false. The disassembled code shows it, too:
0: iconst_0 1: istore_1 2: iconst_0 3: istore_2 4: iconst_0 5: istore_3 6: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 9: iload_1 10: iload_2 11: if_icmpne 18 14: iconst_1 15: goto 19 18: iconst_0 19: iload_3 20: if_icmpne 27 23: iconst_1 24: goto 28 27: iconst_0 28: invokevirtual #3 // Method java/io/PrintStream.println:(Z)V 31: return
This is all well and good, and the original poster was shown code that would work:
(a==b && b==c). However… there were other solutions offered. They include:
(a == b) == c
(a ^ b) == c
a ^ b ^ c
All together now: ugh.
But why? Which ones of those work? Which ones don’t work? (You should probably try to give this some thought before continuing. Be honest with yourself about your answers: nobody else is watching.)
It doesn’t matter.
The reason comes down to code complexity. The simplest solution (
a==b && b==c) lacks a certain elegance, I suppose: it’s very straightforward and very, very simple. The other solutions appeal to a certain mentality, the one that says that you have to know something to use this code; you have to think about them some.
You might not have to think much – but only one has the chance of being right, the
isSame() method, and that assumes it works properly.
Smart coders will code simply; gauge code by the reward it should give.
isSame(), if it accepts multiple types of sequences and has variable arity, might be okay if you can reuse it in multiple scenarios (and it’s needed quite a bit in your code, I guess) — but the others are too complex to really pass a good code review.