introduce
Software Engineer Guidelines for Robert C.Martin's Clean Code The same applies to PHP.It is not a guide to coding style, it guides us to write readable, reusable, and decomposable code in PHP.
Not all guidelines must be strictly followed, even some have become common conventions.This is just a guideline, many of which are years of experience by the Clean Code authors.
Although many developers still use PHP version 5, most of the examples in this article run only under PHP version 7.1 +.
variable
Use meaningful and readable variable names
Unamiable:
$ymdstr = $moment->format('y-m-d');
Amicable:
$currentDate = $moment->format('y-m-d');
Use the same vocabulary for variables of the same type
Unamiable:
getUserInfo(); getUserData(); getUserRecord(); getUserProfile();
Amicable:
getUser();
Use searchable names (Part I)
We read more code than we wrote.So it's important that the code we write needs to be readable and searchable.It's a headache for us to understand variables in programs that don't have names.Make your variables searchable!
Code not readable:
// What does Ghost 448 mean? $result = $serializer->serialize($data, 448);
Readable:
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
Use searchable names (Part 2)
It is bad:
// What does ghost 4 mean? if ($user->access & 4) { // ... }
Good way:
class User { const ACCESS_READ = 1; const ACCESS_CREATE = 2; const ACCESS_UPDATE = 4; const ACCESS_DELETE = 8; } if ($user->access & User::ACCESS_UPDATE) { // do edit ... }
Use explanatory variables
Not good:
$address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches[1], $matches[2]);
General:
That's good, but we still rely heavily on regular expressions.
$address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); [, $city, $zipCode] = $matches; saveCityZipCode($city, $zipCode);
Excellent:
Reduce dependency on regular expressions by naming sub-patterns.
$address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches['city'], $matches['zipCode']);
Avoid nesting too deep and returning early (Part I)
Using too many if else expressions can make the code difficult to understand.
Explicit is better than implicit.
Not good:
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; } else { return false; } } else { return false; } } else { return false; } }
Excellent:
function isShopOpen(string $day): bool { if (empty($day)) { return false; } $openingDays = [ 'friday', 'saturday', 'sunday' ]; return in_array(strtolower($day), $openingDays, true); }
Avoid nesting too deep and returning early (Part 2)
Not good:
function fibonacci(int $n) { if ($n < 50) { if ($n !== 0) { if ($n !== 1) { return fibonacci($n - 1) + fibonacci($n - 2); } else { return 1; } } else { return 0; } } else { return 'Not supported'; } }
Excellent:
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); }
Avoid Psychological Mapping
Don't force your code reader to translate the meaning of variables.
Explicit is better than implicit.
Not good:
$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); }
Excellent:
$locations = ['Austin', 'New York', 'San Francisco']; foreach ($locations as $location) { doStuff(); doSomeOtherStuff(); // ... // ... // ... dispatch($location); }
Do not add unnecessary context
If the class or object name tells you something, don't repeat it in the variable name.
Small Bad:
class Car { public $carMake; public $carModel; public $carColor; //... }
Good way:
class Car { public $make; public $model; public $color; //... }
For more information, visit: