重构简单的功能

时间:2012-12-10 12:31:46

标签: php refactoring

我需要以人类可读的格式显示当前记录状态。 在我的数据库中,我有一个这个字段的int,所以记录可能有状态1,2,3,4 e.t.c

我写了一些代码来向用户显示当前状态:

<?php 
// code to retrieve current status from DB
// ...


if ($status == '1') {
    echo "Current status: Active";
}
if ($status == '2') {
    echo "Current status: Pending";
}
    if ($status == '3') {
    echo "Current status: Inactive";
}

// etc..

?>

这段代码看起来非常难看,但我无法弄清楚如何重构它以使其更有效并且没有一系列无限条件。

5 个答案:

答案 0 :(得分:5)

制作一个数组:

$statvalue=array(1=>'Active',2=>'Pending',3=>'Inactive');
echo("Current status: {$statvalue[$status]}");

答案 1 :(得分:4)

使用数组最好解决这个问题:

function foo($status) {
    $strings = array(
        '1' => "Current status: Active",
        '2' => "Current status: Pending";
        '3' => "Current status: Inactive";
    );

    return $strings[$status];
}

语法要短得多,您可以在以后通过向数组添加键来扩展它。

答案 2 :(得分:2)

尝试Switch声明

switch($status){
  case '1':
   echo "Current status: Active";
   break;

  case '2':
    echo "Current status: Pending";
    break;

 case '3':
    echo "Current status: Inactive";
   break;
 default:
   echo "i is not equal to  1,2 or 3";
}

已删除,因为。更好的方法是JamWaffles answer

答案 3 :(得分:2)

您可以创建一个引用状态的数组:

<?php
$status_cases = ['active', 'pending', 'inactive'];

echo "Current status: ". $status_cases[$status - 1];

答案 4 :(得分:1)

您可以采取一些措施来改善这一点。

首先,许多开发人员更喜欢使用常量值进行比较,如下所示:

if ('1' == $status) {

这使得更难以意外地使用赋值运算符(“=”)而不是相等运算符(“==”),这往往会产生有趣的错误。

其次,正如MortenSickel和Thomas Ruiz所写的那样,用查找替换这种语句是个好主意。 MortenSickel的答案更好,因为它意味着你可以在数组中有间隙,而不必使用任意整数位置来协调你的数组 - 显然总是更好。

然而,我的建议是将状态描述放在数据库中 - 很可能在几个地方需要这些信息(填充数据库的代码,读取它的代码,报告等),以及在多个代码位置之间协调这听起来是个坏主意。