Code is Read More Than Written
Optimize for understanding, not cleverness.
Naming Things
// Bad
$d = 86400;
$arr = getUsers();
function proc($x) {}
// Good
$secondsPerDay = 86400;
$activeUsers = getActiveUsers();
function processPayment($order) {}
Small Functions
// Bad - does too much
function handleOrder($order) {
// validate
// calculate tax
// apply discount
// charge card
// send email
// update inventory
}
// Good - single responsibility
function handleOrder($order) {
$this->validateOrder($order);
$total = $this->calculateTotal($order);
$this->chargeCustomer($order, $total);
$this->sendConfirmation($order);
$this->updateInventory($order);
}
Avoid Nesting
// Bad
function getDiscount($user) {
if ($user) {
if ($user->isPremium()) {
if ($user->ordersCount() > 10) {
return 0.2;
}
}
}
return 0;
}
// Good - early returns
function getDiscount($user) {
if (!$user) return 0;
if (!$user->isPremium()) return 0;
if ($user->ordersCount() <= 10) return 0;
return 0.2;
}
Comments
// Bad - explains what (obvious)
$i++; // increment i
// Good - explains why (not obvious)
$i++; // Skip header row
// Better - code explains itself
$currentRowIndex++; // variable name makes comment unnecessary
Consistency
Pick conventions and follow them:
- camelCase or snake_case
- Tabs or spaces
- Single or double quotes
- Brace placement
Doesn't matter which. Consistency matters.
Delete Dead Code
If it's commented out, delete it. Git remembers.
// Bad
// function oldWay() { ... }
function newWay() { ... }
// Good
function newWay() { ... }
