Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

McCabe Cyclomatic Complexity for switch in Java

I am using a switch statement with 13 cases, each case only has an one line return value.

McCabe paints this in red. Is there an easier way to write a big switch statement? It doesn't seem complex to read, but I don't like the default setting turning red. If other people use the same tool on my code and see red stuff they might think I'm stupid :-)

Edit: I'm mapping different SQL-Types to my own more abstract types, therefore reducing the total amount of types.

case Types.TIME:
    return AbstractDataType.TIME;
case Types.TIMESTAMP:
    return AbstractDataType.TIME;
case Types.DATE:
    return AbstractDataType.TIME;
case Types.BIGINT:
    return AbstractDataType.NUMERIC;
case Types.DECIMAL:
    return AbstractDataType.NUMERIC;

and so on...

like image 276
Franz Kafka Avatar asked Nov 28 '11 03:11

Franz Kafka


People also ask

Does switch case reduce cyclomatic complexity?

Almost invariably, the switch/case statement can be replaced in a way that removes the cyclomatic complexity.

How is McCabe's number calculated in Java?

Calculate cyclomatic complexity in JavaAssign one point to account for the start of the method. Add one point for each conditional construct, such as an "if" condition. Add one point for each iterative structure. Add one point for each case or default block in a switch statement.


1 Answers

You are using code to express what really is data. Just use an enum map or define once for all a constant Dictionary. This way, you are just parametrizing a simple and generic correspondence algorithm, instead of writing a long switch case.

like image 52
Patrick from NDepend team Avatar answered Nov 07 '22 08:11

Patrick from NDepend team