How can the code be improved for better readability and maintenance?
The code can be improved for better readability and maintenance by breaking down the logic into smaller, more modular functions with descriptive names. This will make it easier to understand the code and make future changes. Additionally, using comments to explain the purpose of each section of code can also improve readability.
// Original code
function calculateTotalPrice($quantity, $price) {
$subtotal = $quantity * $price;
$tax = $subtotal * 0.1;
$total = $subtotal + $tax;
return $total;
}
$totalPrice = calculateTotalPrice(10, 20);
echo "Total Price: $" . $totalPrice;
// Improved code
function calculateSubtotal($quantity, $price) {
return $quantity * $price;
}
function calculateTax($subtotal) {
return $subtotal * 0.1;
}
function calculateTotalPrice($quantity, $price) {
$subtotal = calculateSubtotal($quantity, $price);
$tax = calculateTax($subtotal);
$total = $subtotal + $tax;
return $total;
}
$totalPrice = calculateTotalPrice(10, 20);
echo "Total Price: $" . $totalPrice;