月度归档:2013 年一月

奇葩代码重构

让我抓狂的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public static function getFormatContent($code, $arg1='', $arg2='', $arg3='', $arg4='', $arg5='', $arg6='', $arg7='', $arg8='')
{
$format = DictContent::item('message', $code);
if (!empty($format))
return self::formatMessage($format, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $arg7, $arg8);
return '';
}

public static function formatMessage($format, $arg1='', $arg2='', $arg3='', $arg4='', $arg5='', $arg6='', $arg7='', $arg8='')
{
$strResult = $format;
if (strlen(strval($arg1)) > 0)
$strResult = str_replace('\1', $arg1, $strResult);

if (strlen(strval($arg2)) > 0)
$strResult = str_replace('\2', $arg2, $strResult);

if (strlen(strval($arg3)) > 0)
$strResult = str_replace('\3', $arg3, $strResult);

if (strlen(strval($arg4)) > 0)
$strResult = str_replace('\4', $arg4, $strResult);

if (strlen(strval($arg5)) > 0)
$strResult = str_replace('\5', $arg5, $strResult);

if (strlen(strval($arg6)) > 0)
$strResult = str_replace('\6', $arg6, $strResult);

if (strlen(strval($arg7)) > 0)
$strResult = str_replace('\7', $arg7, $strResult);

if (strlen(strval($arg8)) > 0)
$strResult = str_replace('\8', $arg8, $strResult);

$strResult = str_replace('\n', "\n", $strResult);
return $strResult;

}

重构了一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static function getFormatContent($code){
$params = func_get_args();
$format = DictContent::item('message', $code);
if (!empty($format))
return self::formatMessage($format, $params);
return '';
}

private static function formatMessage($format, $params){
$strResult = $format;
foreach($params as $k=>$v){
$strResult = str_replace('\'.$k, $v, $strResult);
}

$strResult = str_replace('
\n', "\n", $strResult);
return $strResult;
}