PHP Coding styles return; in switch/case

后端 未结 6 2133
栀梦
栀梦 2021-02-01 00:13

we\'re trying to implement new coding style guidelines for our team, the php codesniffer is printing an warning on switch case statements when no \"break\" is found like:

<
6条回答
  •  没有蜡笔的小新
    2021-02-01 01:11

    It's perfectly valid to leave out the break when you return from a switch.

    But it's fairly common practise to add explicit breaks to every case as a defensive programming practise.

    switch ($foo) {
        case 1:
            return 1;
            break;
    
        case 2:
            return 2;
            break;
    }
    

    The idea is that should you later change your code in case 1 and remove the return statement, you could forget to add a break.

    That would accidentally cause program flow to fall through to case 2.

    switch ($foo) {
        case 1:
            somethingDifferent();
    
        case 2:
            return 2;
            break;
    }
    

    Falling through case statements is slightly unusual and you should add a comment to your code when you do it to show that it's intentional.

    switch ($foo) {
        case 1:
            somethingDifferentAndWeWantToDoCase2AsWell();
            // fallthrough
    
        case 2:
            return 2;
            break;
    }
    

    As with many defensive programming practises you've got to balance whether the code bloat - which potentially clutters your code and make it less readable - is worth it or not.

提交回复
热议问题