2011-01-21 15 views
0

我們已經與好友討論了下面的代碼和邏輯。我們有處理POST請求的系統(實際上不是REST,只是發佈請求)。看到下面的PHP得到的想法:KISS與heckload的方法

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_encode調用。

感謝。

回答

2

該代碼變得更加自我記錄。每次看到內嵌評論時,都可能提示將代碼提取到其自己的方法中,並將註釋合併到方法名稱中。

該代碼與其他人一起玩。這可能是也可能不是你的考慮因素,但如果有人想要使用200行功能中的10行,那麼他們很可能最終會複製並粘貼它,這對任何人都沒有好處。

在類似的說明中,heckload方法== heck更容易進行單元測試。測試讓聖誕老人開心。