Parenthesis elimination

From Ssdlpedia

Jump to: navigation, search

Parenthesis elimination is a Spartan programming technique reducing token count by making transformations such as

  • removing redundant parenthesis around returned or thrown value, e.g., replacing
return (a);

by

return a;

In Eclipse, and other tools which use the java.util.regex.Pattern library for pattern matching, the search for

\b(return|throw)\s*\(([^{};])\)\s*;

may yield opportunities for such a simplification. The pattern match requires that the code is formatted with the K&R indentation style. Beware though that this pattern also matches statements in which no closing parenthesis can be eliminated such as

return (a+b)*(c+d);

[edit] Cautions

Regular expressions are tricky. Apply caution and care before using a global search and replace with these to modify your code.

  • The regular expressions presented here assume the code is formatted strictly according to the Kernighan and Ritchie indentation style style. To be on the safe side, use and automatic code formatter, such as indent -kr, or Eclipse auto formatting together with the K&R setting.
  • The replacement text does not preserve indentation. Applying the substitution will destroy the carefully indented code. This is yet another reason to use automatic indentation the tool of your choice.
  • Beware that regular expression search may be easily fooled by comments and strings and may therefore produce wrong results: it may fail to recognize correct code which should be substituted; worse, it may change correct code in unexpected ways. It is prudent to inspect each such replacement manually and to apply some automatic checking to increase confidence that a global replacement, even if monitored by a human, did not cause the code to behave in unexpected ways.
Personal tools