开发者

KISS vs. heckload of methods

We've got a discussion with the buddy on the following code and logic. We've got the system that handles the POST requests (not REST actually, just post requests). See the following php to get the idea:

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 panc开发者_开发问答ake 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;
  }
 }

is there any reason to make the methods for each answer? I mean the following onces:

 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!
  }

And use them instead of direct json_encode call.

Thanks.


The code becomes more self documenting. Every time you see an inline comment that could be a hint to extract the code into a method of its own and incorporate the comment in the method name.

The code plays nicer with others. This may or may not be a consideration for you, but if there's someone out there who wants to use 10 lines out of your 200 line function then they'll most likely end up copy and pasting it, which is no fun for anyone.

On a similar note, heckload of methods == heck of a lot easier to unit test. And testing makes Santa happy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜