Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: simplified the example by eliminating array

...

Code Block
bgColor#FFcccc
class BadPrecedence {
  public static void main(String[] args) {
    int number = 17;
    int[] threshold = new int[20];
    threshold[0] = 10;
    number = (number > threshold[0] ? 0 : -2) 
             + ((31 * ++number) * (number = get()));
    // ... 
    if (number == 0) {
      System.out.println("Access granted");
    } else {
      System.out.println("Denied access"); // number = -2
    }
  }

  public static int get() {
    int number = 0;
    // Assign number to non zero value if authorized else 0
    return number;
  }
}

...

Although this code performs as expected, it still represents poor practice by writing to number three times in a single expression.

Code Block
bgColor#ffcccc
int number = 17;

number = ((31 * ++number) * (number=get())) + (number > threshold[0] ? 0 : -2);

Compliant Solution (Order of Evaluation)

...