Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some examples of where using parentheses in a program lowers readability?

I always thought that parentheses improved readability, but in my textbook there is a statement that the use of parentheses dramatically reduces the readability of a program. Does anyone have any examples?

like image 298
Brandon Tiqui Avatar asked Dec 02 '22 06:12

Brandon Tiqui


1 Answers

I can find plenty of counterexamples where the lack of parentheses lowered the readability, but the only example I can think of for what the author may have meant is something like this:

if(((a == null) || (!(a.isSomething()))) && ((b == null) || (!(b.isSomething()))))
{
   // do some stuff
}

In the above case, the ( ) around the method calls is unnecessary, and this kind of code may benefit from factoring out of terms into variables. With all of those close parens in the middle of the condition, it's hard to see exactly what is grouped with what.

boolean aIsNotSomething = (a == null) || !a.isSomething();  // parens for readability
boolean bIsNotSomething = (b == null) || !b.isSomething();  // ditto
if(aIsNotSomething && bIsNotSomething)
{
   // do some stuff
}

I think the above is more readable, but that's a personal opinion. That may be what the author was talking about.

Some good uses of parens:

  • to distinguish between order of operation when behavior changes without the parens
  • to distinguish between order of operation when behavior is unaffected, but someone who doesn't know the binding rules well enough is going to read your code. The good citizen rule.
  • to indicate that an expression within the parens should be evaluated before used in a larger expression: System.out.println("The answer is " + (a + b));

Possibly confusing use of parens:

  • in places where it can't possibly have another meaning, like in front of a.isSomething() above. In Java, if a is an Object, !a by itself is an error, so clearly !a.isSomething() must negate the return value of the method call.
  • to link together a large number of conditions or expressions that would be clearer if broken up. As in the code example up above, breaking up the large paranthetical statement into smaller chunks can allow for the code to be stepped through in a debugger more straightforwardly, and if the conditions/values are needed later in the code, you don't end up repeating expressions and doing the work twice. This is subjective, though, and obviously meaningless if you only use the expressions in 1 place and your debugger shows you intermediate evaluated expressions anyway.
like image 127
Phil Avatar answered Dec 05 '22 03:12

Phil