Refactoring Challenge 1 (Enhanced Code Management in PHP)
2 min readMar 6, 2024
In my previous post, We explored refactoring techniques to improve code quality and readability. I recommend you to review that post from here:
Final refactoring step led to bellow code:
class Order {
private const DISCOUNT_RATE = 0.9;
public function __construct(
private readonly array $items=[]
) {}
public function calculateTotal(): float
{
$subtotal = $this->calculateSubtotal();
return $this->applyDiscount($subtotal);
}
private function calculateSubtotal(): int
{
$subtotal = 0;
foreach ($this->items as $item) {
$subtotal += $item->price;
}
return $subtotal;
}
private function applyDiscount($total): float
{
return $total * self::DISCOUNT_RATE;
}
}
A valid question arises: How do we know that calculateSubtotal
returns an integer? The answer lies in the implicit contract that prices are represented as either integers or floats. However, this leads to another question: If it's just a verbal contract, isn't…