How can I reduce the Cyclomatic Complexity of this?

前端 未结 5 965
情深已故
情深已故 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:21

    Never had a goal to "reduce the cyclomatic complexity", though there were times when I was paid by LOC.

    You code is "good enough". My eyes stumble on brackets, so I'd sacrifice a bit of performance and did the following (providing types A, B and so on are not in the same hierarchy):

    receive(Object object) {
        if (object intanceof ObjectTypeA) doSomethingA();
        if (object instanceof ObjectTypeB) doSomethingB();
        ...
    

    or (if they are in the same hierarchy):

    receive(Object object) {
        if (object intanceof ObjectTypeA) { doSomethingA(); return; }
        if (object instanceof ObjectTypeB) { doSomethingB(); return; }
        ...
    

    Don't know if it would reduce the cyclomatic thingy, and couldn't care less.

提交回复
热议问题