:bathtub: Clean Code concepts adapted for PHP
:bathtub: Clean Code concepts adapted for PHP
Software engineering principles, from Robert C. Martin's book Clean Code, adapted for PHP. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in PHP.
Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.
Inspired from clean-code-javascript.
Although many developers still use PHP 5, most of the examples in this article only work with PHP 7.1+.
Bad:
$ymdstr = $moment->format('y-m-d');Good:
$currentDate = $moment->format('y-m-d');Bad:
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();Good:
getUser();We will read more code than we will ever write. It's important that the code we do write is readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable.
Bad:
// What the heck is 448 for?
$result = $serializer->serialize($data, 448);Good:
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);Bad:
class User
{
// What the heck is 7 for?
public $access = 7;
}
// What the heck is 4 for?
if ($user->access & 4) {
// ...
}
// What's going on here?
$user->access ^= 2;Good:
class User
{
public const ACCESS_READ = 1;
public const ACCESS_CREATE = 2;
public const ACCESS_UPDATE = 4;
public const ACCESS_DELETE = 8;
// User as default can read, create and update something
public $access = self::ACCESS_READ | self::ACCESS_CREATE | self::ACCESS_UPDATE;
}
if ($user->access & User::ACCESS_UPDATE) {
// do edit ...
}
// Deny access rights to create something
$user->access ^= User::ACCESS_CREATE;Bad:
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches[1], $matches[2]);Not bad:
It's better, but we are still heavily dependent on regex.
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
[, $city, $zipCode] = $matches;
saveCityZipCode($city, $zipCode);Good:
Decrease dependence on regex by naming subpatterns.
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches['city'], $matches['zipCode']);Too many if-else statements can make your code hard to follow. Explicit is better than implicit.
Bad:
function isShopOpen($day): bool
{
if ($day) {
if (is_string($day)) {
$day = strtolower($day);
if ($day === 'friday') {
return true;
} elseif ($day === 'saturday') {
return true;
} elseif ($day === 'sunday') {
return true;
}
return false;
}
return false;
}
return false;
}Good:
function isShopOpen(string $day): bool
{
if (empty($day)) {
return false;
}
$openingDays = ['friday', 'saturday', 'sunday'];
return in_array(strtolower($day), $openingDays, true);
}Bad:
function fibonacci(int $n)
{
if ($n < 50) {
if ($n !== 0) {
if ($n !== 1) {
return fibonacci($n - 1) + fibonacci($n - 2);
}
return 1;
}
return 0;
}
return 'Not supported';
}Good:
function fibonacci(int $n): int
{
if ($n === 0 || $n === 1) {
return $n;
}
if ($n >= 50) {
throw new Exception('Not supported');
}
return fibonacci($n - 1) + fibonacci($n - 2);
}Don’t force the reader of your code to translate what the variable means. Explicit is better than implicit.
Bad:
$l = ['Austin', 'New York', 'San Francisco'];
for ($i = 0; $i < count($l); $i++) {
$li = $l[$i];
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `$li` for again?
dispatch($li);
}Good:
$locations = ['Austin', 'New York', 'San Francisco'];
foreach ($locations as $location) {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch($location);
}If your class/object name tells you something, don't repeat that in your variable name.
Bad:
class Car
{
public $carMake;
public $carModel;
public $carColor;
//...
}Good:
class Car
{
public $make;
public $model;
public $color;
//...
}Not good:
The simple comparison will convert the string into an integer.
$a = '42';
$b = 42;
if ($a != $b) {
// The expression will always pass
}The comparison $a != $b returns FALSE but in fact it's TRUE!
The string 42 is different than the integer 42.
Good:
The identical comparison will compare type and value.
$a = '42';
$b = 42;
if ($a !== $b) {
// The expression is verified
}The comparison $a !== $b returns TRUE.
Null coalescing is a new operator introduced in PHP 7. The null coalescing operator ?? has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.
Bad:
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}Good:
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';Not good:
This is not good because $breweryName can be NULL.
function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
{
// ...
}Not bad:
This opinion is more understandable than the previous version, but it better controls the value of the variable.
function createMicrobrewery($name = null): void
{
$breweryName = $name ?: 'Hipster Brew Co.';
// ...
}Good:
You can use type hinting and be sure that the $breweryName will not be NULL.
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
// ...
}Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.
Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it's not, most of the time a higher-level object will suffice as an argument.
Bad:
class Questionnaire
{
public function __construct(
string $firstname,
string $lastname,
string $patronymic,
string $region,
string $district,
string $city,
string $phone,
string $email
) {
//Code Error
Unable to create PR due to "Validation failed: must be a collaborator"
Cleen code
Premier jet du dictionnaire de données
"Prefer composition over inheritance": Why you don't use traits?
Book PHp
Problem in the fibonacci function
adding ndonesian translation section + Refactor code under collapsible markdown
Define constants in those methods where you use, not globally
introduction of mocking on "Functions should only be one level of abstraction" should be removed