[英]Can this code be improved to avoid repetition?
下面的代码是用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.");
}
明显改善:
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.");
}
您可以执行以下操作:
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.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.