How can I reduce the Cyclomatic Complexity of this?

前端 未结 5 969
情深已故
情深已故 2020-12-16 13:37

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 O         


        
5条回答
  •  再見小時候
    2020-12-16 14:23

    Why the need to reduce the complexity? It is a simple enough pattern that any competent developer would see it as a trivial function.

    I would probably write it this way

        if (object instanceof ObjectTypeA) 
        {
            doSomethingA();
        }
        else if (object instanceof ObjectTypeB) 
        {
            doSomethingB();
        }
        else if (object instanceof ObjectTypeC) 
        {
            doSomethingC();
        }
    

    If it is to to meet some esoteric need to "CC must be less than x", then the overarching rule that the standards are there to ensure maintainable code would mean this is acceptable no matter how high the CC gets.

提交回复
热议问题