PHP is our current language of choice for the projects we handle. Currently we are using php 7.3.9
. One of the many principles we follow in our development is ‘Clean Code’.
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Martin Fowler
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Martin Fowler
Some Clean Code principles we follow:
-
Meaningful and Pronounceable Variable Names
We try to use names that can have meaning and readable names.
Instead of$variable = $date->format('y-m-d');
we try hard to find a name that describes the value the most:
$dateOfToday = $date->format('y-m-d');
-
Searchable Names
We try to make searchable values.
Instead of$responseCode = $response->getValue(200);
we try hard to find names to values we need
$responseCode = $response->getValue(OK_RESPONSE);
-
Type-Hinting and Return Type-Hinting
The larger the application, the more the code. The more the code, the more important it is to have a clear overview on what methods accept as parameters, what they do and what they return, without having to study each method all over again. So instead of having:
function myFunction($input) { // do something }
you will find in our code something like:
function isWorkingDay(string $input): bool { // do somthing }
-
Minimum Nesting and Early Returns
To make the code readable and understandable we reduce the complexity by avoiding nested if-else statements where possible. So instead of having
function isWorkingDay(string $input): bool { $nameOfDay = strtolower($nameOfDay); if($nameOfDay === 'monday') { return true; } elseif($nameOfDay === 'tuesday') { return true; } elseif($nameOfDay === 'wednesday') { return true; } elseif($nameOfDay === 'thursday') { return true; } elseif($nameOfDay === 'friday') { return true; } return false; }
you will find in our code something like:
const WORKING_DAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']; function isWorkingDay(string $input): bool { return in_array(strtolower($input), WORKING_DAYS)); }
another example of this is, instead of:
function fibonacci(int $n) { if ($n < 50) { if ($n != 0) { if ($n != 1) { return fibonacci($n -1) + fibonacci($n -2); } else { if ($n < 0) { return 'Not supported'; } else { return 1; } } } else return 0; } } else { return 'Not supported'; } }
we would do this as follows:
function fibonacci(int $n): int { if ($n === 0 || $n === 1) { return 1; } if ($n < 0 || $n > 50) { throw ne \Exception('Integer must be between 0 and 50'); } return fibonacci($n - 1) + fibonacci($n - 2); }