Clean functions

Clean code is code that the next reader can change without fear. In PHP the two habits that carry most of it are small functions with honest names and one copy of each piece of logic.

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().

<?php function show(array $rows): void { foreach ($rows as $r) { echo "<div>" . htmlspecialchars($r["t"]) . "</div>", PHP_EOL; } } $rows = [["t" => "Ada"], ["t" => "Grace"]]; show($rows);

php show.php

<div>Ada</div>
<div>Grace</div>

The function escapes each title with htmlspecialchars(), formats and prints in one pass, and the short key t carries no meaning for the reader. The clean version separates building a card from printing the list:

<?php function cardHtml(array $row): string { return "<div>" . htmlspecialchars($row["title"]) . "</div>"; } function showCards(array $rows): void { foreach ($rows as $row) { echo cardHtml($row), PHP_EOL; } } $rows = [["title" => "Ada"], ["title" => "Grace"]]; showCards($rows);

php clean.php

<div>Ada</div>
<div>Grace</div>

The output is the same, and now a test can call cardHtml() with one row and check the string without any output. The loop of the second function knows nothing about markup, so a change of the card stays in one place.

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.

Exercises

  1. Rename $r in show.php to $row and decide whether the function got clearer.
  2. Add a second field to the card, for example a score, without touching the loop of showCards.php.
  3. Find a function in your own code that needs a comment inside it and split it.
  4. Write two functions that differ by one array key and merge them with a parameter.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. When does a function try to do too much?

    Answer

    When its body needs comments to explain each block

    A block that needs its own explanation is a function of its own, and the outer one becomes shorter.

  2. Which name fits a boolean value?

    Answer

    isActive

    A question with is reads as a boolean, and the word and would hide two values in one name.

  3. Two blocks differ by one value. What is the clean fix?

    Answer

    Extract the value as a parameter and keep one copy

    One copy with a parameter cannot drift, and the change of the value stays at the call.

  4. Why are short functions easier to test?

    Answer

    Each test covers one behavior of one function

    A single job gives a single case to check, so a failure names the function that broke.

  5. What does this program print? <?php function show(array $rows): void { foreach ($rows as $r) { echo "<div>" . htmlspecialchars($r["t"]) . "</div>", PHP_EOL; } } show([["t" => "Ada"]]);

    Answer

    <div>Ada</div>

    The function prints the div around the escaped value, and one row gives one line.

  6. What does this program print? <?php function cardHtml(array $row): string { return "<div>" . htmlspecialchars($row["title"]) . "</div>"; } echo cardHtml(["title" => "Ada"]);

    Answer

    <div>Ada</div>

    The function returns the markup and echo prints it, so the browser would show a div with the text.

  7. What does this program print? <?php function label(string $s): string { return strtoupper($s); } echo label("ada");

    Answer

    ADA

    strtoupper turns every letter into its upper case form.

  8. What does this program print? <?php function isActive(bool $flag): string { return $flag ? "yes" : "no"; } echo isActive(true);

    Answer

    yes

    The ternary takes the first branch for true and returns the string yes.

  9. A function named doStuff() loads a user, sends a mail and writes a log. What does the name hide?

    Answer

    Three jobs that want three functions

    The vague name covers a whole sequence, so no reader can tell what calling it will do.

  10. What does this program print? <?php function card(array $row): string { return "<div>" . htmlspecialchars($row["title"]) . "</div>"; } echo card(["title" => "Ada"]) . card(["title" => "Grace"]);

    Answer

    <div>Ada</div><div>Grace</div>

    Each call returns one div and the two returns are printed one after the other on the same line.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev