09 Feb 2022 - nicolas
Life is simple, so is computer programming.
excerpt_separator:
Set a convention then stick to it in your project.
For instance, here is what I do:
Functions names begin with a verb then a complement:
function verbComplement() {
// Your logic
}
function isValid(myFunctionParameters) {
// Your logic
}
Boolean variables also start with a verb:
$isValid = true;
$hasTags = true;
$isProgrammingAwesome = true;
Dates have a suffix At
:
$createdAt = (new DateTimeImmutable());
$updatedAt = (new DateTimeImmutable());
$deletedAt = (new DateTimeImmutable());
SOLID stands for:
Single responsibility principle
A class should have one and only one reason to change, meaning that a class should have only one job.
Open/Closed principle
Objects or entities should be open for extension but closed for modification.
Liskov substitution principle
Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.
Interface segregation principle
A client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.
Dependency inversion principle
Entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.
source: Digital Ocean post
At least, if you apply the S, it will be a huge improvement.
In if
conditions, instead of using else
statements, we can avoid each states that are unwanted like so:
public function handleRedApples(Basket $fruitBasket): void
{
if ($fruitBasket->isEmpty()) {
throw new RuntimeException("Basket {$fruitBasket->getId()} is empty.");
}
$errors = [];
array_map(function ($fruit) use ($errors) {
if ('apple' !== $fruit->getVariety()) {
$errors[] = "{$fruit->getVariety()} is not an apple.";
continue;
}
if ('red' !== $fruit->getColor()) {
$errors[] = "{$fruit->getColor()} is not red.";
continue;
}
$this->handle($fruit);
}, $fruitBasket->getFruits());
if ([] !== $errors) {
throw new RuntimeException(json_encode($errors));
}
}