title: Optimizing a method with boolean flag
body: <p>I have a method whose purpose is to retrieve collection items.  </p>
  
  <p>A collection can contain a mix of items, let's say: pens, pencils, and papers. </p>
  
  <p>The 1st parameter allows me to tell the method to retrieve only the itemTypes I pass (e.g, just pens and pencils).</p>
  
  <p>The 2nd parameter flags the function to use the collection's default item types, instead.</p>
  
  <pre><code>getCollectionItems($itemTypes,$useCollectionDefaultItemTypes) {
      foreach() {
          foreach() {
              foreach() {
                 // lots of code...
  
                 if($useCollectionDefaultItemTypes) {
                   // get collection's items using collection-&gt;itemTypes
                 }
                 else {
                   // get collection's items using $itemTypes
                 }
  
                 // lots of code...
              }
          }    
      }
  }
  </code></pre>
  
  <p>What feels odd is that if I set the $useCollectionDefaultItemTypes to true, there is no need for the function to use the first parameter. I was considering refactoring this method into two such as:</p>
  
  <pre><code>getCollectionItems($itemTypes); // get the items using $itemTypes
  getCollectionItems(); // get the items using default settings
  </code></pre>
  
  <p>The problem is that the methods will have lots of duplicate code except for the if-statement area.</p>
  
  <p>Is there a better way to optimize this?</p>