Tuesday, January 24, 2023

Operator precedence

Started reading the book Clean Code. Interesting read. But as always, be critical on what you read. Here is an excerpt from the book that I don't agree:

- - >8 - -

Another use for white space is to accentuate the precedence of operators.


public class Quadratic {
  public static double root1(double a, double b, double c) {
    double determinant = determinant(a, b, c);
    return (-b + Math.sqrt(determinant)) / (2*a);
  }
  public static double root2(int a, int b, int c) {
    double determinant = determinant(a, b, c);
    return (-b - Math.sqrt(determinant)) / (2*a);
  }
  private static double determinant(double a, double b, double c) {
    return b*b - 4*a*c;
  }
}

- - 8< - -
 

Using spacing to indicate precedence could mislead others that are reading the code for debugging. For example:

a||b && c

is actually evaluated as a || (b && c). Using spaces to indicate what the programmer *thinks* the precedence is doesn't mean it is how the computer will execute the logic.

Use parentheses to express how you *want* the logic to be executed. And always put a space before and after any operator.