PHP编码样式返回;开关/外壳 [英] PHP Coding styles return; in switch/case

查看:188
本文介绍了PHP编码样式返回;开关/外壳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在为我们的团队实施新的编码风格指南,php codesniffer在没有发现break时在switch case语句上打印警告,例如:

  switch($ foo){
case 1:
return 1;
case 2:
return 2;
默认值:
return 3;
}

有什么好的理由使用:

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

c> c> 开关返回



但是对于每个 case 添加显式 break 作为防御性程序设计练习。

 开关($ foo){
case 1:
return 1;
break;

case 2:
return 2;
break;
}

这个想法是,如果你以后更改你的代码 case 1 并删除return语句,您可能会忘记添加 break



这将意外导致程序流向情况2

  switch($ foo){
case 1:
somethingDifferent();

case 2:
return 2;
break;
}

通过case语句稍有不同,您应该向代码添加注释

  switch($ foo){
case 1:
somethingDifferentAndWeWantToDoCase2AsWell();
//下降

情况2:
return 2;
break;
}

与许多防御性编程做法一样,您必须平衡代码膨胀 - 这可能会杂乱你的代码,使其更少的可读性 - 值得或不。


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.

这篇关于PHP编码样式返回;开关/外壳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆