mccabe java,Java中的切换的McCabe Cyclomatic Complexity

博主分享了在代码中使用包含13个case的大switch语句时遇到的问题,即McCabe工具将其标记为红色,可能引发他人对其代码质量的误解。文章探讨了简化switch语句的方法,包括使用EnumMap和减少返回语句。提出了一种解决方案:通过合并具有相同返回类型的case,减少switch的复杂性。这不仅可以降低Cyclomatic复杂度,还能提供不同的编码风格。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值