可以改进此代码以避免重复吗?

时间:2015-10-28 01:51:12

标签: php cakephp dry

下面的代码是用php编写的switch语句。在每种情况下,行$historical_term = $this->MonthlyCurves->getHistorical($term, $start_date, $end_date);都会重复。这违反了DRY(不要重复自己)的原则。有没有办法改进代码以遵守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.");
            } 

2 个答案:

答案 0 :(得分: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.");
}

答案 1 :(得分: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.");
            } 
相关问题