How do I reduce the McCabe Cyclomatic Complexity of this code

190 views Asked by At

I have the java below. This is called from a menu, where the user enters a number (opcaoMenu) corresponding to an option, and it call a method based on this option. This code has cyclomatic complexity of 8, and I want to reduce it, but I have no clue how.

private static EstruturaStack decisaoMenu(EstruturaStack topoStack, int opcaoMenu) {
    if (opcaoMenu == 1) {
        topoStack = empilharChapa(topoStack);
    }
    if (opcaoMenu == 2) {
        consultarTodasChapas(topoStack);
    }
    if (opcaoMenu == 3) {
        topoStack = empilhar(topoStack);
    }
    if (opcaoMenu == 4) {
        topoStack = esvaziarPatio(topoStack);
    }
    if (opcaoMenu == 5) {
        verificarQuantidade(topoStack);
    }
    if (opcaoMenu == 6) {
        filtrarPorPedido(topoStack);
    }
    if (opcaoMenu == 7) {
        exibirMensagem("MENSAGEM DO PROGRAMA:\n\nOpção em desenvolvimento!", "Mensagem do Programa");
    }
    return topoStack;
}

Thanks

1

There are 1 answers

0
yacc On

If it's granted that opcaoMenu always is in the range 1..7 then you could use an if-else compound to alleviate the last if. This will reduce the complexity by 1.

if (opcaoMenu == 1) {
    topoStack = empilharChapa(topoStack);
}
else if (opcaoMenu == 2) {
    consultarTodasChapas(topoStack);
}
else if (opcaoMenu == 3) {
    topoStack = empilhar(topoStack);
}
else if (opcaoMenu == 4) {
    topoStack = esvaziarPatio(topoStack);
}
else if (opcaoMenu == 5) {
    verificarQuantidade(topoStack);
}
else if (opcaoMenu == 6) {
    filtrarPorPedido(topoStack);
}
else {
    exibirMensagem("MENSAGEM DO PROGRAMA:\n\nOpção em desenvolvimento!", "Mensagem do Programa");
}