【问题标题】:Can this code be improved to avoid repetition?可以改进此代码以避免重复吗?
【发布时间】:2015-10-28 01:51:12
【问题描述】:

下面的代码是一个用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.");
            } 

【问题讨论】:

    标签: php cakephp dry


    【解决方案1】:

    明显改善:

    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.");
    }
    

    【讨论】:

    • 感谢所有有效的众多答案。我最喜欢明显的。最容易理解。
    【解决方案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.");
                } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多