How can I reduce the Cyclomatic Complexity of this?

Nathan picture Nathan · May 2, 2011 · Viewed 57.5k times · Source

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...
                }
            }
        }
    }
}

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

Answer

laz picture laz · May 2, 2011

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?