如何使这个代码组织得更好

时间:2011-08-02 16:12:18

标签: php logic design-patterns

这是代码......我的if,else语句很长...如何分开?有什么建议吗?谢谢。

public function receiveMsg(aMsg){
    if($aMsg instanceof LoginMsg){
         $this->callingSomeMethod();         //should I separate this code into other class/ object? 
         $this->callingAnotherMethod();  //should I separate this code into other class/ object? 

         $aMsg = new RespondLoginMsg();  //should I separate this code into other class/ object? 
         $this->sendMsg($aMsg);          //should I separate this code into other class/ object? 

    }else if(aMsg instanceof LogoutMsg){
         $this->callingSomeMethod();     //should I separate this code into another class/ object? 

         $aMsg = new RespondLogoutMsg();     //should I separate this code into another class/ object? 
         $this->sendMsg($aMsg);               //should I separate this code into another class/ object? 


    }else if/*****bababab***/

    /*****many else if here (up to 200 msg+ , just upload 2 here.)***/


}

3 个答案:

答案 0 :(得分:2)

也许开关更容易阅读?并且sendMsg可以移出它,只需使用你在swtich / if中设置的$ aMsg对象。

$strMessageClass=get_class($aMsg);
switch ($strMessageClass) {
    case 'LoginMsg':
        $this->callingSomeMethod();
        $aMsg = new RespondLoginMsg();
    case 'RespondLogoutMsg':
        $this->callingAnotherMethod();
        $aMsg = RespondLogoutMsg();
    default:
        // If you have any..
}
$this->sendMsg($aMsg);

答案 1 :(得分:0)

如果这就是所谓的那么长的if / else语句,我没有看到任何根本错误。

如果你发现它是一个眼睛,为什么不定义每个if / else块的内容作为它自己的函数?

您还可以考虑消除冗余。如果他们都以

结束
     $aMsg = new RespondLoginMsg();
     $this->sendMsg($aMsg);

然后没有必要在每个区块中重复它。

答案 2 :(得分:0)

除了摆脱过多的间距和换行符,我不知道这里的问题是什么。您需要多少个不同的类来检查项目是否是实例?在我看来,这里的名单非常有限。如果你没有任何超过3或4个if / else语句,那么只需保留if / else即可。否则使用开关或循环。

你能更具体地了解你想要完成的任务吗?

这是一个稍微清洁的代码版本。

public function receiveMsg(aMsg) {
  if ($aMsg instanceof LoginMsg) {
    $this->callingSomeMethod(); 
    $this->callingAnotherMethod();

    $aMsg = new RespondLoginMsg();
    $this->sendMsg($aMsg);
  }
  else if (aMsg instanceof LogoutMsg) {
    $this->callingSomeMethod(); 

    $aMsg = new RespondLogoutMsg();
    $this->sendMsg($aMsg);
  }
  else if { /*****bababab***/

  }
  /*****many else if here***/
}