2011-01-21 4 views
0

次のコードとロジックについてバディと議論しています。 POSTリクエストを処理するシステムがあります(RESTではなく、リクエストを投稿するだけです)。考えを知るには、次のPHPを参照してください。KISSとメソッドのヘックロード

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行を使用したい人がいる場合は、コピーと貼り付けを終了する可能性が高くなります。

同様の注意点では、メソッドのヘックロード==単なる単体テストよりも簡単です。そして、テストはサンタを幸せにします。

関連する問題