Coding style 亲吻vs.大量的方法

Coding style 亲吻vs.大量的方法,coding-style,Coding Style,我们已经与好友讨论了以下代码和逻辑。我们有一个处理POST请求的系统(实际上不是REST,只是POST请求)。请参阅以下php以了解这一想法: class Pancake { public function servePancake() { if (/* check something on the kitchen*/) { echo json_encode(array('status' => 'error', 'message' => 'kitchen off

我们已经与好友讨论了以下代码和逻辑。我们有一个处理POST请求的系统(实际上不是REST,只是POST请求)。请参阅以下php以了解这一想法:

class Pancake {
  public function servePancake()
  {
   if (/* check something on the kitchen*/) {
    echo json_encode(array('status' => 'error', 'message' => 'kitchen offline'));
    exit;
   }

   if (/* check something else on the kitchen */) {
    echo json_encode(array('status' => 'error', 'message' => 'Santa hates you, no pancakes this time'));
    exit;
   }  

   if (/* check if there's something else in the menu */) {
    echo json_encode(array(
     'status' => 'weDoHaveMenuYouShouldCheckItOut', 
     'message' => 'See the menu for a pancake flavor you wish',
     'pancakeTypes' => array('cherry', 'blueberry', 'blackberry')
    ));
    exit;
   }

   // And so on with lot's of options, but pretty simple inside

   // if everything went fine
   echo json_encode(array('status' => 'ok', 'message' => 'Here is your pancake'));
   exit;
  }
 }
是否有任何理由为每个答案制定方法?我指的是以下几点:

 protected function respondWithMenu($message, $menu)
  {
   // basically the same json_encode and exit;
  }

  protected function respondWithSuccess($message);
  {
   // Status is succes + same json_encode
  }

  protected function respondWithError($message)
  {
   // Status is error + same json_encode
  }

  protected function respondWithSomethingElse($message, $somethingElse)
  {
   // adding something else to the response
   // and then.... gues what?
   // yeah, json_encode, you're correct!
  }
并使用它们代替直接的json_编码调用


谢谢。

代码变得更加自我记录。每次看到内联注释时,都会提示您将代码提取到自己的方法中,并将注释合并到方法名称中

代码对其他人的作用更好。这对你来说可能是一个考虑因素,也可能不是,但是如果有人想使用你200行函数中的10行,那么他们很可能会复制并粘贴它,这对任何人来说都没有乐趣

类似地,heckload of methods==heck更容易进行单元测试。测试让圣诞老人高兴