Clean functions
Small functions win
A function should do one thing and say so in its name. Short functions are easy to test, easy to name, and easy to delete. When a function needs a comment to explain a block inside it, that block wants to be its own function.
Name things well
Names carry meaning: verbs for actions, nouns for values, questions for booleans. sendReport() beats doStuff(); isActive beats flag. If a name needs the word and, it hides two functions - split them.
Big function vs clean version
Compare a blob that loads, formats, and prints with small steps that compose. Same result, but each step can be tested and reused alone. A real helper built this way is card_from_db().
function show(array $rows): void
{
foreach ($rows as $r) {
echo "<div>" . htmlspecialchars($r["t"]) . "</div>";
}
}
The clean version separates building a card from printing the list:
function cardHtml(array $row): string
{
return "<div>" . htmlspecialchars($row["title"]) . "</div>";
}
function showCards(array $rows): void
{
foreach ($rows as $row) {
echo cardHtml($row);
}
}
Spot duplication
Duplication is a bug waiting for one copy to change. When two blocks differ by one value, extract the value as a parameter and keep one copy. The patterns are catalogued in Deduplication in PHP.
Next: Debugging
Автор статьи: Arthur Isaev