Method for calculating shipping cost I'm trying to optimize the following method. Any suggestions on how this can be done better? The shipping cost is based on weight and the total cost of products. Following are the conditions for calculating cost.


When order is under $100, and all items under 10 lb, then shipping is $5 flat.
When order is $100 or more, and each individual item is under 10 lb, then shipping is free.
Items over 10 lb always cost $20 each to ship.




public function addShippingCost($subtotal)
        {
            $shipCost = 0;
            $totalWeight = 0;
            $itemUnder10lb = true;
            foreach ($this-&gt;products as $product) {
                if($product-&gt;getWeight() &gt; 10){
                    $shipCost += $this::RATE_HEAVY;
                    $itemUnder10lb = false;
                }
                $totalWeight += $product-&gt;getWeight();
            }
            //When order is under $100, and all items under 10 lb, then shipping is $5 flat
            //When order is $100 or more, and each individual item is under 10 lb, then shipping is free
            //Items over 10 lb always cost $20 each to ship

            if($subtotal &gt; 100 &amp;&amp; $itemUnder10lb)
                return $this::RATE_FREE;
            elseif($subtotal &lt; 100 &amp;&amp; $totalWeight &lt; 10)
                return $this::RATE_FLAT;
            elseif($itemUnder10lb == false)
                return shipCost;
        }
What if you have an order, that is 


> 10lb in total weight
&lt; $100 in subtotal 
has no product with > 10lb? 


Your method would not return anything in that case.

Here's my patched solution:

public function addShippingCost($subtotal) {
    $shipCost = 0;
    $weightSum = 0;
    $allItemsUnder10lb = true;

    foreach ($this-&gt;products as $product) {
        if($product-&gt;getWeight() &gt; 10){
            $shipCost += $this::RATE_HEAVY;
            $allItemsUnder10lb = false;
        }
        $weightSum += $product-&gt;getWeight();
    }

    if ($subtotal &lt; 100 &amp;&amp; $weightSum &lt; 10) {
        $shipCost = $this::RATE_FLAT;
    } 

    if ($subtotal &gt;= 100 &amp;&amp; $allItemsUnder10lb) {
        $shipCost = $this::RATE_FREE;
    }

    return $shipCost;
}