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:
switch ($foo) { case 1: return 1; case 2: return 2; default: return 3; } is there any good reason to use :
switch ($foo) { case 1: return 1; break; } ?? the break is never reached ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With