【问题标题】:Removing duplicate code from code single/two-dimensional arrays从代码单/二维数组中删除重复代码
【发布时间】:2020-03-23 13:25:52
【问题描述】:

我目前遇到的问题是我使用包含其他数组的数组。下面是我当前的代码。然而问题是我执行了 100 次相同的代码,唯一的区别是当我循环遍历我循环的数组内部的数组时我需要的 $anotherOtherIndex。

如果有人能够通过消除重复代码来减少所需代码量,那将对我有很大帮助。

for( $index = 0; $index < $endOfLoop; $index++ ) {        
            if(true) {
                $myVariable = arrayWithArrays[$index][$anotherIndex]
                x100...
            }else{
                $myVariable = arrayWithArrays[$index][$anotherIndex][$anotherOtherIndex]
                x100...
}

伪代码解决方案(那将是完美的,而我们现在都不存在完美的;)):

for( $index = 0; $index < $endOfLoop; $index++ ) {        
            $myVariable = arrayWithArrays[$index][$anotherIndex][?????]
}


【问题讨论】:

    标签: php arrays code-duplication


    【解决方案1】:

    你可以设置主要部分,只在条件下进一步进入数组

    for( $i = 0; $i < $endOfLoop; $i++ ) {        
        $myVariable = arrayWithArrays[$index][$anotherIndex]
    
        if(false) {
            $myVariable = $myVariable[$anotherOtherIndex]
        }
    }
    

    【讨论】:

    • 这确实改进了我的代码,因为没有 else 语句了。但是,我最终还是得到了 100 行代码,它们 90% 完全相同;(
    • 你能说明下几次重复是什么吗?这样可能更容易理解可以删除进一步重复的地方(如果可能的话)
    • 可以,但是和例子一模一样。唯一的区别是在我的代码中有不同的(更不清楚的)变量名。
    猜你喜欢
    • 2013-08-15
    • 2020-02-26
    • 1970-01-01
    • 2017-11-06
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多