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...
解决方案
I don't know that much about McCabe tools. One of the things Cyclomatic complexity considers is multiple exit points.
I like the EnumMap idea.
If a switch is going to be used, you could have a result variable and do away with all the return statements. You can also collapse all the source values that have the same result type:
result = null;
case Types.TIME:
case Types.DATE:
case Types.TIMESTAMP: result = AbstractDataType.TIME
// etc.
return result;
I think this reduces the cyclomatic complexity, regardless of what anyone thinks about it as style. And it is a different way to write the statement, though whether it is easier you should judge.