如何降低Cyclomatic Complexity? [英] How can I reduce the Cyclomatic Complexity of this?

查看:184
本文介绍了如何降低Cyclomatic Complexity?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法接收一个Object并根据它检测到的对象类型做一些事情:

I have a method that receives an Object and does something based on what type of object it detects:

void receive(Object object) {
    if (object instanceof ObjectTypeA) {
        doSomethingA();
    }
    else {
        if (object instanceof ObjectTypeB) {
            doSomethingB();
        }
        else {
            if (object instanceof ObjectTypeC) {
                doSomethingC();
            }
            else {
                if (object instanceof ObjectTypeD) {
                    doSomethingD();
                }
                else {
                    // etc...
                }
            }
        }
    }
}

如何降低Cyclomatic复杂度?我四处搜索但找不到任何有用的东西。

How can I reduce the Cyclomatic Complexity? I searched around but couldn't find anything too useful.

推荐答案

难道你不能利用面向对象的方法吗?创建一个具有 doSomething()方法的接口,然后创建实现所需行为的子类?然后调用 object.doSomething()会执行相应的行为吗?

Can't you leverage an object-oriented approach for this? Create an interface that has the doSomething() method then create subclasses that implement the desired behavior? Then calling object.doSomething() would execute the appropriate behavior?

这篇关于如何降低Cyclomatic Complexity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆