两种类似功能的模式,无需复制代码

时间:2014-09-16 21:34:46

标签: php design-patterns

除了存在变量反转之外,我有两个几乎相同的函数。我想知道如何在没有重复代码的情况下处理这个问题。

例如:

public static function getMajorRelative($tonality){
            $result = array_search($tonality,self::$_minorTonalities);
            return self::$_majorTonalities[$result];
}

public static function getMinorRelative($tonality){
        $result = array_search($tonality,self::$_majorTonalities);
        return self::$_minorTonalities[$result];
}

任何人都有类似的受孕问题吗?

谢谢,

菲利普

3 个答案:

答案 0 :(得分:1)

您始终可以传入要从以下位置接收结果的数组:

public static function getRelative($tonality, $return_array) {
    //If returning minor, search major; Else, search minor.
    $array_to_search = ($return_array === self::$_minorTonalities ? self::$_majorTonalities : $_minorTonalities);
    $result = array_search($tonality, $array_to_search);
    return $return_array[$result];
}

答案 1 :(得分:0)

2条相似(不完全相同)的代码行并不是真正的重复,但您可以这样做:

protected static function getRelative($tonality, $tonalities1, $tonalities2) {
    $result = array_search($tonality, $tonalities1);
    return $tonalities2[$result];
}

public static function getMajorRelative($tonality){
    return self::getRelative($tonality, self::$_minorTonalities, self::$_majorTonalities);
}

public static function getMinorRelative($tonality){
    return self::getRelative($tonality, self::$_majorTonalities, self::$_minorTonalities);
}

如果真的很重要

如果您的数组中没有$ tonality的值,您可能还需要一些异常处理

答案 2 :(得分:0)

我不确定还有很多需要改进的地方。但如果你愿意,你可以把它写成一个函数:

public static function getRelative($chord,$tonality)
{
  $varName = '_'.($chord == 'major' ? 'major' : 'minor').'Tonalities';
  $result = array_search($tonality,self::${$varName});
  return self::${$varName}[$result];
}

您可以将其命名为:

getRelative('major',$tonality);
getRelative('minor',$tonality);