1

Is it considered to be good practice or even safe to check if a condition can be evaluated and then evaluating the expression in the same if statement?

For example:

int[] values = new int[] { 1, 2, 3, 4 }
int index = 4;
if (index < values.length && values[index] == 4) {
    System.out.println("value is 4")
}

In this example the condition is values[index] == 4 and I am using index < values.length to check if it is safe to call it. However, I am doing this in the same if statement. Is it ok to do this?

otoomey
  • 939
  • 1
  • 14
  • 31
  • && and || are there for this reason. If you use & or |, all the statements are evaluated. I don't see any drawbacks in your code. – marco Nov 03 '17 at 11:23
  • As said [here](https://stackoverflow.com/questions/16033085/if-statement-with-where-the-first-condition-needs-to-be-true-before-testing-t), yes, it is safe. The second condition is tested only if the first one is verified – Oneiros Nov 03 '17 at 11:23
  • This example is too short to be meaningful and actually used in production. – Adam Siemion Nov 03 '17 at 11:24
  • @AdamSiemion It is a short example that demonstrates the problem, no? That doesn't mean that it has to be useful. – otoomey Nov 03 '17 at 11:28

1 Answers1

2

Yes, this is correct approach, because in Java there is mechanism called short-circuit evaluation (called also lazy evaluation). That means JVM checks for first condition and if this is false JVM knows that no matter what result is in second condition it won't change anything, so second condition is skipped. In your example if index is greater than values.length, the whole if statement is false, so second condition is omitted.


Edit:

As Coffee Ninja mentioned, there is significant difference between bitwise operators (&,|) and logical operators (&&,||). Technically result should be the same, but bitwise operators are evaluated eager, so both sides are proceeded. This may result in OutOfBoundException in your example.
What's more, bitwise operators have lower precedence, so if you accidentally mix logical and bitwise operators, you can receive different results.

Simon
  • 129
  • 8
  • 1
    To make your answer even better and informative, I suggest you add a reference to the bitwise `&` operator, which works like `&&` on boolean values except it doesn't short-circuit. – ttzn Nov 03 '17 at 11:34