I have just tried to write my first ever Groovy script and noticed that the following method does not work as I would expect it to (at first glance at least).
boolean isComment(String line)
{
line = line.trim();
return
line.startsWith('//') ||
line.startsWith('/*') ||
line.startsWith('*') ||
line.startsWith('*/');
}
I realized that (due to the fact that semicolons are optional in Groovy) the method body is in fact:
- An assignment to the “line” variable.
- An empty return statement (!), which evaluates to and returns false.
- Four other (non-reachable) independent statements.
To me, the inability to format expressions in order to improve readability seems as quite a drawback.
What is the correct Groovy way to express such a method?
Aside from the logic not actually indicating what lines are comments, the easiest is this:
IMO this is easier to comprehend quickly anyway.
Skipping the unnecessary return also eliminates the issue:
Another option would be to wrap the conditional in parens:
Another option would be to use something closer to this: