-
Bug
-
Resolution: Fixed
-
High
-
None
-
None
Problem:
Consider the following code:
def create(boolean b) { switch (b) { case true: new Integer(10) break case false: new String("abc") break } }
- switch statement is the last statement in function, so it's value is being returned from a function call
- new Integer() / new String() are last statements before 'break' which is a function's exit point
- thus 10 or "abc" are returned
Clover instruments code as follows:
def create(boolean b) { recorder.inc(0); switch (b) { case true: recorder.inc(1); new Integer(10) recorder.inc(2); break case false: recorder.inc(3); new String("abc") recorder.inc(4); break } }
- as a consequence, the last statement before 'break' becomes recorder.inc(), which returns void; as a result the create() function returns null
Workaround:
Use return instead of break in a switch statement, e.g.:
case true: return new Integer(10) // no break
Fix:
- do not add recorder.inc() before 'break'; drawback of the solution: we loose tracking of empty breaks, see below.
def foo(int i) { switch (i) { case 1: recorder.inc(1); println("one") /*recorder.inc(2); not added*/ break; case 2: case 3: /*recorder.inc(3); not added*/ break; } } foo(1) foo(2)
in the code above it would be nice to have "case2: case 3: recorder.inc(3); break;" colored in green, despite that code makes nothing ...
NOTE: This works with Groovy 1.6.5 or higher, because the "switch as an expression" feature was implemented in Groovy 1.6.5: