Parentheses and precedenceThis week, I will strive to be better at explaining the problem scope, while heroically and miraculously maintaining brevity.
I used to be annoyed at seeing extraneous parentheses with the ternary conditional operator pair
? :, but then I discovered that the PHP language designers decided to break precedence (see example #3). So I have stopped twitching as much as I used to when seeing parentheses galore in that context.
In Perl Best Practices, Damian Conway notes that even though the low-precedence logic operators
ormay seem nicer, they can confuse the reader regarding the intended meaning of the code. But he does not — as far as I can recall or find — address how these relates to parentheses and precedence (I suppose that should be "parentheses && precedence").
I start twitching when someone insists on using parentheses like this (imagine that the example was more convoluted):
if (expr1 ||That does not help understanding. It confuses me, as the read, regarding your intentions. Is there a piece of code missing, perhaps a little bit of
(expr2 && expr3) ||
Sometimes, I even see misguidedly mixed-in letter-literal operators:
if (expr1 or
(expr2 && expr3) or
I much prefer seeing
if (expr1 ||or
expr2 && expr3 ||
if (expr1depending on what floats your boat in the most stylish way imaginable.
|| expr2 && expr3
I would have thought that the logical and/or/not part of operator precedence would be easy to understand. It is essentially the same in most programming languages: Ruby, Python, Perl, Java, C, ... and not even PHP managed to mess this one up.
The chance that anyone is going to be confused by your code because of these parentheses not being there is far, far smaller than the chance that they are going to be confused by their presence.
I have heard the defense "but the code is so non-obvious that I had to add them!" Well, make your code obvious instead.