2015-10-28 79 views
1

下面的代碼是用php編寫的switch語句。行$historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);在所有情況下重複。這違反了DRY(不要重複自己)的原則。有什麼方法可以改進代碼以堅持幹嗎?此代碼是否可以改進以避免重複?

switch ($term) 
      { 
       case "1": 
        $term = 'XXX_1_year';     
        $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); 
        break; 
       case "2": 
        $term = 'XXX_2_year';     
        $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); 
        break; 
       case "5": 
        $term = 'XXX_5_year'; 
        $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); 
        break; 
       default: 
        print ("Invalid parameter."); 
      } 

回答

4

明顯改善:

switch ($term) { 
    case "1": 
    case "2": 
    case "5": 
     $term = 'XXX_'.$term'_year';     
     $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); 
     break; 
    default: 
     print ("Invalid parameter."); 
} 

if (($term == '1') || ($term == '2') || ($term == '5')) { 
    $term = 'XXX_'.$term'_year';     
    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); 
} else { 
    print ("Invalid parameter."); 
} 

if (in_array($term, array('1', '2', '5'))) { 
    $term = 'XXX_'.$term'_year';     
    $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); 
} else { 
    print ("Invalid parameter."); 
} 
+0

感謝所有工作的衆多答案。我更喜歡最明顯的一個。這是最容易理解的。 – user781486

2

你可以做這樣的事情:

switch ($term) 
      {  
       case "1": 
       case "2": 
       case "5": 
        $term = 'XXX_'.$term.'_year'; 
        $historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date); 
        break; 
       default: 
        print ("Invalid parameter."); 
      }