使用布尔标志优化方法

时间:2012-01-26 04:01:56

标签: optimization methods

我有一个方法,其目的是检索集合项。

一个集合可以包含各种项目,比方说:钢笔,铅笔和纸张。

第一个参数允许我告诉方法只检索我传递的itemTypes(例如,只是钢笔和铅笔)。

第二个参数标记了使用集合的默认项类型的函数。

getCollectionItems($itemTypes,$useCollectionDefaultItemTypes) {
    foreach() {
        foreach() {
            foreach() {
               // lots of code...

               if($useCollectionDefaultItemTypes) {
                 // get collection's items using collection->itemTypes
               }
               else {
                 // get collection's items using $itemTypes
               }

               // lots of code...
            }
        }    
    }
}

奇怪的是,如果我将$ useCollectionDefaultItemTypes设置为true,则该函数不需要使用第一个参数。我正在考虑将这种方法重构为两个,例如:

getCollectionItems($itemTypes); // get the items using $itemTypes
getCollectionItems(); // get the items using default settings

问题是除了if语句区域外,这些方法会有很多重复的代码。

有没有更好的方法来优化它?

3 个答案:

答案 0 :(得分:1)

当您不使用时,将$itemTypes作为null传递。请if语句检查$itemTypes === null;如果是,请使用默认设置。

如果这是php,我认为它是,你可以让你的方法签名function getCollectionItems($itemTypes = null),然后你可以打电话给getCollectionItems(),它会像打字getCollectionItems(null)一样打电话给它

答案 1 :(得分:1)

编写使用这样的标志的方法通常是个坏主意。我已经看过写在几个地方(here在#16,鲍勃叔叔here和其他地方)。它使得该方法难以理解,阅读和重构。

另一种设计是使用closures。您的代码可能如下所示:

$specificWayOfProcessing = function($a) {
  //do something with each $a
};

getCollectionItems($processer) {
  foreach() {
    foreach() {
      foreach() {
        // lots of code...
        $processor(...)
        // lots of code...
      }
    }    
  }
}

getCollectionItems($specificWayOfProcessing);

这种设计更好,因为

  1. 它更灵活。当你需要在三种不同的事物之间做出决定时会发生什么?
  2. 您现在可以更轻松地测试循环内的代码
  3. 现在更容易阅读,因为最后一行告诉您“正在使用特定的处理方式获取收集项目” - 它读起来就像一个英文句子。

答案 2 :(得分:1)

是的,有更好的方法可以做到这一点 - 虽然这个问题不是优化问题,而是风格问题。 (重复的代码对性能影响不大!)

按照原始想法实现这一点的最简单方法是使getCollectionItems()的无参数形式定义默认参数,然后调用需要参数的版本:

getCollectionItems($itemTypes) {
    foreach() {
        foreach() {
            foreach() {
                // lots of code...
                // get collection's items using $itemTypes
            }
            // lots of code...
        }
    }    
}

getCollectionItems() {
    getCollectionItems(collection->itemTypes)
}

根据您使用的语言,您甚至可以使用默认参数将这些语言折叠为单个函数定义:

getCollectionItems($itemTypes = collection->itemTypes) {
    foreach() {
        foreach() {
            foreach() {
                // lots of code...
                // get collection's items using $itemTypes
            }
            // lots of code...
        }
    }    
}

这样做的好处是可以清楚地表达您的原创想法,即如果提供的话,您会使用$itemTypes,如果没有,则使用collection->itemTypes

(当然,这确实假设您正在讨论单个“集合”,而不是让其中一个foreach次迭代迭代集合。如果是,那么使用{的想法{1}}值很好。)

相关问题