McCabe Cyclomatic Complexity for switch in Java

五迷三道 提交于 2019-12-05 03:43:31

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.

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.

+1 for the Map idea...

Something like this:

Initialize the map

Map<Types, AbstractDataType> map = new HashMap<Types, AbstractDataType>();
map.put(Types.TIME, AbstractDataTypes.TIME);
// and so on

Then in your code simple do

return map.get(sqlTimeType);

An even better solution however would be to include this mapping in the enum itself so you would be able to do assuming you don't have control over the Sql enum types...

AbstractDataTypes.fromSqlType(timeType);

and if you do:

sqlTimeType.getAbstractType();

Encapsulated and Re-usable :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!