Giter Site home page Giter Site logo

clean-code-php's Introduction

Clean Code PHP

Table of Contents

  1. Introduction
  2. Variables
  3. Comparison
  4. Functions
  5. Objects and Data Structures
  6. Classes
  7. SOLID
  8. Don’t repeat yourself (DRY)
  9. Translations

Introduction

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+.

Variables

Use meaningful and pronounceable variable names

Bad:

$ymdstr = $moment->format('y-m-d');

Good:

$currentDate = $moment->format('y-m-d');

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:

getUserInfo();
getUserData();
getUserRecord();
getUserProfile();

Good:

getUser();

⬆ back to top

Use searchable names (part 1)

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);

Use searchable names (part 2)

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;

⬆ back to top

Use explanatory variables

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']);

⬆ back to top

Avoid nesting too deeply and return early (part 1)

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);
}

⬆ back to top

Avoid nesting too deeply and return early (part 2)

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);
}

⬆ back to top

Avoid Mental Mapping

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);
}

⬆ back to top

Don't add unneeded context

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;

    //...
}

⬆ back to top

Comparison

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.

⬆ back to top

Null coalescing operator

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';

⬆ back to top

Functions

Use default arguments instead of short circuiting or conditionals

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
{
    // ...
}

⬆ back to top

Function arguments (2 or fewer ideally)

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
    ) {
        // ...
    }
}

Good:

class Name
{
    private $firstname;

    private $lastname;

    private $patronymic;

    public function __construct(string $firstname, string $lastname, string $patronymic)
    {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
        $this->patronymic = $patronymic;
    }

    // getters ...
}

class City
{
    private $region;

    private $district;

    private $city;

    public function __construct(string $region, string $district, string $city)
    {
        $this->region = $region;
        $this->district = $district;
        $this->city = $city;
    }

    // getters ...
}

class Contact
{
    private $phone;

    private $email;

    public function __construct(string $phone, string $email)
    {
        $this->phone = $phone;
        $this->email = $email;
    }

    // getters ...
}

class Questionnaire
{
    public function __construct(Name $name, City $city, Contact $contact)
    {
        // ...
    }
}

⬆ back to top

Function names should say what they do

Bad:

class Email
{
    //...

    public function handle(): void
    {
        mail($this->to, $this->subject, $this->body);
    }
}

$message = new Email(...);
// What is this? A handle for the message? Are we writing to a file now?
$message->handle();

Good:

class Email
{
    //...

    public function send(): void
    {
        mail($this->to, $this->subject, $this->body);
    }
}

$message = new Email(...);
// Clear and obvious
$message->send();

⬆ back to top

Functions should only be one level of abstraction

When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.

Bad:

function parseBetterPHPAlternative(string $code): void
{
    $regexes = [
        // ...
    ];

    $statements = explode(' ', $code);
    $tokens = [];
    foreach ($regexes as $regex) {
        foreach ($statements as $statement) {
            // ...
        }
    }

    $ast = [];
    foreach ($tokens as $token) {
        // lex...
    }

    foreach ($ast as $node) {
        // parse...
    }
}

Bad too:

We have carried out some of the functionality, but the parseBetterPHPAlternative() function is still very complex and not testable.

function tokenize(string $code): array
{
    $regexes = [
        // ...
    ];

    $statements = explode(' ', $code);
    $tokens = [];
    foreach ($regexes as $regex) {
        foreach ($statements as $statement) {
            $tokens[] = /* ... */;
        }
    }

    return $tokens;
}

function lexer(array $tokens): array
{
    $ast = [];
    foreach ($tokens as $token) {
        $ast[] = /* ... */;
    }

    return $ast;
}

function parseBetterPHPAlternative(string $code): void
{
    $tokens = tokenize($code);
    $ast = lexer($tokens);
    foreach ($ast as $node) {
        // parse...
    }
}

Good:

The best solution is move out the dependencies of parseBetterPHPAlternative() function.

class Tokenizer
{
    public function tokenize(string $code): array
    {
        $regexes = [
            // ...
        ];

        $statements = explode(' ', $code);
        $tokens = [];
        foreach ($regexes as $regex) {
            foreach ($statements as $statement) {
                $tokens[] = /* ... */;
            }
        }

        return $tokens;
    }
}

class Lexer
{
    public function lexify(array $tokens): array
    {
        $ast = [];
        foreach ($tokens as $token) {
            $ast[] = /* ... */;
        }

        return $ast;
    }
}

class BetterPHPAlternative
{
    private $tokenizer;
    private $lexer;

    public function __construct(Tokenizer $tokenizer, Lexer $lexer)
    {
        $this->tokenizer = $tokenizer;
        $this->lexer = $lexer;
    }

    public function parse(string $code): void
    {
        $tokens = $this->tokenizer->tokenize($code);
        $ast = $this->lexer->lexify($tokens);
        foreach ($ast as $node) {
            // parse...
        }
    }
}

⬆ back to top

Don't use flags as function parameters

Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.

Bad:

function createFile(string $name, bool $temp = false): void
{
    if ($temp) {
        touch('./temp/' . $name);
    } else {
        touch($name);
    }
}

Good:

function createFile(string $name): void
{
    touch($name);
}

function createTempFile(string $name): void
{
    touch('./temp/' . $name);
}

⬆ back to top

Avoid Side Effects

A function produces a side effect if it does anything other than take a value in and return another value or values. A side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a stranger.

Now, you do need to have side effects in a program on occasion. Like the previous example, you might need to write to a file. What you want to do is to centralize where you are doing this. Don't have several functions and classes that write to a particular file. Have one service that does it. One and only one.

The main point is to avoid common pitfalls like sharing state between objects without any structure, using mutable data types that can be written to by anything, and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers.

Bad:

// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
$name = 'Ryan McDermott';

function splitIntoFirstAndLastName(): void
{
    global $name;

    $name = explode(' ', $name);
}

splitIntoFirstAndLastName();

var_dump($name);
// ['Ryan', 'McDermott'];

Good:

function splitIntoFirstAndLastName(string $name): array
{
    return explode(' ', $name);
}

$name = 'Ryan McDermott';
$newName = splitIntoFirstAndLastName($name);

var_dump($name);
// 'Ryan McDermott';

var_dump($newName);
// ['Ryan', 'McDermott'];

⬆ back to top

Don't write to global functions

Polluting globals is a bad practice in many languages because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to have configuration array? You could write global function like config(), but it could clash with another library that tried to do the same thing.

Bad:

function config(): array
{
    return [
        'foo' => 'bar',
    ];
}

Good:

class Configuration
{
    private $configuration = [];

    public function __construct(array $configuration)
    {
        $this->configuration = $configuration;
    }

    public function get(string $key): ?string
    {
        // null coalescing operator
        return $this->configuration[$key] ?? null;
    }
}

Load configuration and create instance of Configuration class

$configuration = new Configuration([
    'foo' => 'bar',
]);

And now you must use instance of Configuration in your application.

⬆ back to top

Don't use a Singleton pattern

Singleton is an anti-pattern. Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.
  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.
  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no for unit tests. Why? Because each unit test should be independent from the other.

There is also very good thoughts by Misko Hevery about the root of problem.

Bad:

class DBConnection
{
    private static $instance;

    private function __construct(string $dsn)
    {
        // ...
    }

    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    // ...
}

$singleton = DBConnection::getInstance();

Good:

class DBConnection
{
    public function __construct(string $dsn)
    {
        // ...
    }

    // ...
}

Create instance of DBConnection class and configure it with DSN.

$connection = new DBConnection($dsn);

And now you must use instance of DBConnection in your application.

⬆ back to top

Encapsulate conditionals

Bad:

if ($article->state === 'published') {
    // ...
}

Good:

if ($article->isPublished()) {
    // ...
}

⬆ back to top

Avoid negative conditionals

Bad:

function isDOMNodeNotPresent(DOMNode $node): bool
{
    // ...
}

if (! isDOMNodeNotPresent($node)) {
    // ...
}

Good:

function isDOMNodePresent(DOMNode $node): bool
{
    // ...
}

if (isDOMNodePresent($node)) {
    // ...
}

⬆ back to top

Avoid conditionals

This seems like an impossible task. Upon first hearing this, most people say, "how am I supposed to do anything without an if statement?" The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, "well that's great but why would I want to do that?" The answer is a previous clean code concept we learned: a function should only do one thing. When you have classes and functions that have if statements, you are telling your user that your function does more than one thing. Remember, just do one thing.

Bad:

class Airplane
{
    // ...

    public function getCruisingAltitude(): int
    {
        switch ($this->type) {
            case '777':
                return $this->getMaxAltitude() - $this->getPassengerCount();
            case 'Air Force One':
                return $this->getMaxAltitude();
            case 'Cessna':
                return $this->getMaxAltitude() - $this->getFuelExpenditure();
        }
    }
}

Good:

interface Airplane
{
    // ...

    public function getCruisingAltitude(): int;
}

class Boeing777 implements Airplane
{
    // ...

    public function getCruisingAltitude(): int
    {
        return $this->getMaxAltitude() - $this->getPassengerCount();
    }
}

class AirForceOne implements Airplane
{
    // ...

    public function getCruisingAltitude(): int
    {
        return $this->getMaxAltitude();
    }
}

class Cessna implements Airplane
{
    // ...

    public function getCruisingAltitude(): int
    {
        return $this->getMaxAltitude() - $this->getFuelExpenditure();
    }
}

⬆ back to top

Avoid type-checking (part 1)

PHP is untyped, which means your functions can take any type of argument. Sometimes you are bitten by this freedom and it becomes tempting to do type-checking in your functions. There are many ways to avoid having to do this. The first thing to consider is consistent APIs.

Bad:

function travelToTexas($vehicle): void
{
    if ($vehicle instanceof Bicycle) {
        $vehicle->pedalTo(new Location('texas'));
    } elseif ($vehicle instanceof Car) {
        $vehicle->driveTo(new Location('texas'));
    }
}

Good:

function travelToTexas(Vehicle $vehicle): void
{
    $vehicle->travelTo(new Location('texas'));
}

⬆ back to top

Avoid type-checking (part 2)

If you are working with basic primitive values like strings, integers, and arrays, and you use PHP 7+ and you can't use polymorphism but you still feel the need to type-check, you should consider type declaration or strict mode. It provides you with static typing on top of standard PHP syntax. The problem with manually type-checking is that doing it will require so much extra verbiage that the faux "type-safety" you get doesn't make up for the lost readability. Keep your PHP clean, write good tests, and have good code reviews. Otherwise, do all of that but with PHP strict type declaration or strict mode.

Bad:

function combine($val1, $val2): int
{
    if (! is_numeric($val1) || ! is_numeric($val2)) {
        throw new Exception('Must be of type Number');
    }

    return $val1 + $val2;
}

Good:

function combine(int $val1, int $val2): int
{
    return $val1 + $val2;
}

⬆ back to top

Remove dead code

Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase. If it's not being called, get rid of it! It will still be safe in your version history if you still need it.

Bad:

function oldRequestModule(string $url): void
{
    // ...
}

function newRequestModule(string $url): void
{
    // ...
}

$request = newRequestModule($requestUrl);
inventoryTracker('apples', $request, 'www.inventory-awesome.io');

Good:

function requestModule(string $url): void
{
    // ...
}

$request = requestModule($requestUrl);
inventoryTracker('apples', $request, 'www.inventory-awesome.io');

⬆ back to top

Objects and Data Structures

Use object encapsulation

In PHP you can set public, protected and private keywords for methods. Using it, you can control properties modification on an object.

  • When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
  • Makes adding validation simple when doing a set.
  • Encapsulates the internal representation.
  • Easy to add logging and error handling when getting and setting.
  • Inheriting this class, you can override default functionality.
  • You can lazy load your object's properties, let's say getting it from a server.

Additionally, this is part of Open/Closed principle.

Bad:

class BankAccount
{
    public $balance = 1000;
}

$bankAccount = new BankAccount();

// Buy shoes...
$bankAccount->balance -= 100;

Good:

class BankAccount
{
    private $balance;

    public function __construct(int $balance = 1000)
    {
      $this->balance = $balance;
    }

    public function withdraw(int $amount): void
    {
        if ($amount > $this->balance) {
            throw new \Exception('Amount greater than available balance.');
        }

        $this->balance -= $amount;
    }

    public function deposit(int $amount): void
    {
        $this->balance += $amount;
    }

    public function getBalance(): int
    {
        return $this->balance;
    }
}

$bankAccount = new BankAccount();

// Buy shoes...
$bankAccount->withdraw($shoesPrice);

// Get balance
$balance = $bankAccount->getBalance();

⬆ back to top

Make objects have private/protected members

  • public methods and properties are most dangerous for changes, because some outside code may easily rely on them and you can't control what code relies on them. Modifications in class are dangerous for all users of class.
  • protected modifier are as dangerous as public, because they are available in scope of any child class. This effectively means that difference between public and protected is only in access mechanism, but encapsulation guarantee remains the same. Modifications in class are dangerous for all descendant classes.
  • private modifier guarantees that code is dangerous to modify only in boundaries of single class (you are safe for modifications and you won't have Jenga effect).

Therefore, use private by default and public/protected when you need to provide access for external classes.

For more information you can read the blog post on this topic written by Fabien Potencier.

Bad:

class Employee
{
    public $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

$employee = new Employee('John Doe');
// Employee name: John Doe
echo 'Employee name: ' . $employee->name;

Good:

class Employee
{
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function getName(): string
    {
        return $this->name;
    }
}

$employee = new Employee('John Doe');
// Employee name: John Doe
echo 'Employee name: ' . $employee->getName();

⬆ back to top

Classes

Prefer composition over inheritance

As stated famously in Design Patterns by the Gang of Four, you should prefer composition over inheritance where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition. The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can.

You might be wondering then, "when should I use inheritance?" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:

  1. Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).
  2. You can reuse code from the base classes (Humans can move like all animals).
  3. You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).

Bad:

class Employee
{
    private $name;

    private $email;

    public function __construct(string $name, string $email)
    {
        $this->name = $name;
        $this->email = $email;
    }

    // ...
}

// Bad because Employees "have" tax data.
// EmployeeTaxData is not a type of Employee

class EmployeeTaxData extends Employee
{
    private $ssn;

    private $salary;

    public function __construct(string $name, string $email, string $ssn, string $salary)
    {
        parent::__construct($name, $email);

        $this->ssn = $ssn;
        $this->salary = $salary;
    }

    // ...
}

Good:

class EmployeeTaxData
{
    private $ssn;

    private $salary;

    public function __construct(string $ssn, string $salary)
    {
        $this->ssn = $ssn;
        $this->salary = $salary;
    }

    // ...
}

class Employee
{
    private $name;

    private $email;

    private $taxData;

    public function __construct(string $name, string $email)
    {
        $this->name = $name;
        $this->email = $email;
    }

    public function setTaxData(EmployeeTaxData $taxData): void
    {
        $this->taxData = $taxData;
    }

    // ...
}

⬆ back to top

Avoid fluent interfaces

A Fluent interface is an object oriented API that aims to improve the readability of the source code by using Method chaining.

While there can be some contexts, frequently builder objects, where this pattern reduces the verbosity of the code (for example the PHPUnit Mock Builder or the Doctrine Query Builder), more often it comes at some costs:

  1. Breaks Encapsulation.
  2. Breaks Decorators.
  3. Is harder to mock in a test suite.
  4. Makes diffs of commits harder to read.

For more information you can read the full blog post on this topic written by Marco Pivetta.

Bad:

class Car
{
    private $make = 'Honda';

    private $model = 'Accord';

    private $color = 'white';

    public function setMake(string $make): self
    {
        $this->make = $make;

        // NOTE: Returning this for chaining
        return $this;
    }

    public function setModel(string $model): self
    {
        $this->model = $model;

        // NOTE: Returning this for chaining
        return $this;
    }

    public function setColor(string $color): self
    {
        $this->color = $color;

        // NOTE: Returning this for chaining
        return $this;
    }

    public function dump(): void
    {
        var_dump($this->make, $this->model, $this->color);
    }
}

$car = (new Car())
    ->setColor('pink')
    ->setMake('Ford')
    ->setModel('F-150')
    ->dump();

Good:

class Car
{
    private $make = 'Honda';

    private $model = 'Accord';

    private $color = 'white';

    public function setMake(string $make): void
    {
        $this->make = $make;
    }

    public function setModel(string $model): void
    {
        $this->model = $model;
    }

    public function setColor(string $color): void
    {
        $this->color = $color;
    }

    public function dump(): void
    {
        var_dump($this->make, $this->model, $this->color);
    }
}

$car = new Car();
$car->setColor('pink');
$car->setMake('Ford');
$car->setModel('F-150');
$car->dump();

⬆ back to top

Prefer final classes

The final keyword should be used whenever possible:

  1. It prevents an uncontrolled inheritance chain.
  2. It encourages composition.
  3. It encourages the Single Responsibility Principle.
  4. It encourages developers to use your public methods instead of extending the class to get access to protected ones.
  5. It allows you to change your code without breaking applications that use your class.

The only condition is that your class should implement an interface and no other public methods are defined.

For more informations you can read the blog post on this topic written by Marco Pivetta (Ocramius).

Bad:

final class Car
{
    private $color;

    public function __construct($color)
    {
        $this->color = $color;
    }

    /**
     * @return string The color of the vehicle
     */
    public function getColor()
    {
        return $this->color;
    }
}

Good:

interface Vehicle
{
    /**
     * @return string The color of the vehicle
     */
    public function getColor();
}

final class Car implements Vehicle
{
    private $color;

    public function __construct($color)
    {
        $this->color = $color;
    }

    public function getColor()
    {
        return $this->color;
    }
}

⬆ back to top

SOLID

SOLID is the mnemonic acronym introduced by Michael Feathers for the first five principles named by Robert Martin, which meant five basic principles of object-oriented programming and design.

Single Responsibility Principle (SRP)

As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of times you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.

Bad:

class UserSettings
{
    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function changeSettings(array $settings): void
    {
        if ($this->verifyCredentials()) {
            // ...
        }
    }

    private function verifyCredentials(): bool
    {
        // ...
    }
}

Good:

class UserAuth
{
    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function verifyCredentials(): bool
    {
        // ...
    }
}

class UserSettings
{
    private $user;

    private $auth;

    public function __construct(User $user)
    {
        $this->user = $user;
        $this->auth = new UserAuth($user);
    }

    public function changeSettings(array $settings): void
    {
        if ($this->auth->verifyCredentials()) {
            // ...
        }
    }
}

⬆ back to top

Open/Closed Principle (OCP)

As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.

Bad:

abstract class Adapter
{
    protected $name;

    public function getName(): string
    {
        return $this->name;
    }
}

class AjaxAdapter extends Adapter
{
    public function __construct()
    {
        parent::__construct();

        $this->name = 'ajaxAdapter';
    }
}

class NodeAdapter extends Adapter
{
    public function __construct()
    {
        parent::__construct();

        $this->name = 'nodeAdapter';
    }
}

class HttpRequester
{
    private $adapter;

    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
    }

    public function fetch(string $url): Promise
    {
        $adapterName = $this->adapter->getName();

        if ($adapterName === 'ajaxAdapter') {
            return $this->makeAjaxCall($url);
        } elseif ($adapterName === 'httpNodeAdapter') {
            return $this->makeHttpCall($url);
        }
    }

    private function makeAjaxCall(string $url): Promise
    {
        // request and return promise
    }

    private function makeHttpCall(string $url): Promise
    {
        // request and return promise
    }
}

Good:

interface Adapter
{
    public function request(string $url): Promise;
}

class AjaxAdapter implements Adapter
{
    public function request(string $url): Promise
    {
        // request and return promise
    }
}

class NodeAdapter implements Adapter
{
    public function request(string $url): Promise
    {
        // request and return promise
    }
}

class HttpRequester
{
    private $adapter;

    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
    }

    public function fetch(string $url): Promise
    {
        return $this->adapter->request($url);
    }
}

⬆ back to top

Liskov Substitution Principle (LSP)

This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)." That's an even scarier definition.

The best explanation for this is if you have a parent class and a child class, then the base class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly get into trouble.

Bad:

class Rectangle
{
    protected $width = 0;

    protected $height = 0;

    public function setWidth(int $width): void
    {
        $this->width = $width;
    }

    public function setHeight(int $height): void
    {
        $this->height = $height;
    }

    public function getArea(): int
    {
        return $this->width * $this->height;
    }
}

class Square extends Rectangle
{
    public function setWidth(int $width): void
    {
        $this->width = $this->height = $width;
    }

    public function setHeight(int $height): void
    {
        $this->width = $this->height = $height;
    }
}

function printArea(Rectangle $rectangle): void
{
    $rectangle->setWidth(4);
    $rectangle->setHeight(5);

    // BAD: Will return 25 for Square. Should be 20.
    echo sprintf('%s has area %d.', get_class($rectangle), $rectangle->getArea()) . PHP_EOL;
}

$rectangles = [new Rectangle(), new Square()];

foreach ($rectangles as $rectangle) {
    printArea($rectangle);
}

Good:

The best way is separate the quadrangles and allocation of a more general subtype for both shapes.

Despite the apparent similarity of the square and the rectangle, they are different. A square has much in common with a rhombus, and a rectangle with a parallelogram, but they are not subtypes. A square, a rectangle, a rhombus and a parallelogram are separate shapes with their own properties, albeit similar.

interface Shape
{
    public function getArea(): int;
}

class Rectangle implements Shape
{
    private $width = 0;
    private $height = 0;

    public function __construct(int $width, int $height)
    {
        $this->width = $width;
        $this->height = $height;
    }

    public function getArea(): int
    {
        return $this->width * $this->height;
    }
}

class Square implements Shape
{
    private $length = 0;

    public function __construct(int $length)
    {
        $this->length = $length;
    }

    public function getArea(): int
    {
        return $this->length ** 2;
    }
}

function printArea(Shape $shape): void
{
    echo sprintf('%s has area %d.', get_class($shape), $shape->getArea()).PHP_EOL;
}

$shapes = [new Rectangle(4, 5), new Square(5)];

foreach ($shapes as $shape) {
    printArea($shape);
}

⬆ back to top

Interface Segregation Principle (ISP)

ISP states that "Clients should not be forced to depend upon interfaces that they do not use."

A good example to look at that demonstrates this principle is for classes that require large settings objects. Not requiring clients to set up huge amounts of options is beneficial, because most of the time they won't need all of the settings. Making them optional helps prevent having a "fat interface".

Bad:

interface Employee
{
    public function work(): void;

    public function eat(): void;
}

class HumanEmployee implements Employee
{
    public function work(): void
    {
        // ....working
    }

    public function eat(): void
    {
        // ...... eating in lunch break
    }
}

class RobotEmployee implements Employee
{
    public function work(): void
    {
        //.... working much more
    }

    public function eat(): void
    {
        //.... robot can't eat, but it must implement this method
    }
}

Good:

Not every worker is an employee, but every employee is a worker.

interface Workable
{
    public function work(): void;
}

interface Feedable
{
    public function eat(): void;
}

interface Employee extends Feedable, Workable
{
}

class HumanEmployee implements Employee
{
    public function work(): void
    {
        // ....working
    }

    public function eat(): void
    {
        //.... eating in lunch break
    }
}

// robot can only work
class RobotEmployee implements Workable
{
    public function work(): void
    {
        // ....working
    }
}

⬆ back to top

Dependency Inversion Principle (DIP)

This principle states two essential things:

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend on abstractions.

This can be hard to understand at first, but if you've worked with PHP frameworks (like Symfony), you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.

Bad:

class Employee
{
    public function work(): void
    {
        // ....working
    }
}

class Robot extends Employee
{
    public function work(): void
    {
        //.... working much more
    }
}

class Manager
{
    private $employee;

    public function __construct(Employee $employee)
    {
        $this->employee = $employee;
    }

    public function manage(): void
    {
        $this->employee->work();
    }
}

Good:

interface Employee
{
    public function work(): void;
}

class Human implements Employee
{
    public function work(): void
    {
        // ....working
    }
}

class Robot implements Employee
{
    public function work(): void
    {
        //.... working much more
    }
}

class Manager
{
    private $employee;

    public function __construct(Employee $employee)
    {
        $this->employee = $employee;
    }

    public function manage(): void
    {
        $this->employee->work();
    }
}

⬆ back to top

Don’t repeat yourself (DRY)

Try to observe the DRY principle.

Do your absolute best to avoid duplicate code. Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic.

Imagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc. If you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them. If you only have one list, there's only one place to update!

Often you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you to have two or more separate functions that do much of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class.

Getting the abstraction right is critical, that's why you should follow the SOLID principles laid out in the Classes section. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself updating multiple places any time you want to change one thing.

Bad:

function showDeveloperList(array $developers): void
{
    foreach ($developers as $developer) {
        $expectedSalary = $developer->calculateExpectedSalary();
        $experience = $developer->getExperience();
        $githubLink = $developer->getGithubLink();
        $data = [$expectedSalary, $experience, $githubLink];

        render($data);
    }
}

function showManagerList(array $managers): void
{
    foreach ($managers as $manager) {
        $expectedSalary = $manager->calculateExpectedSalary();
        $experience = $manager->getExperience();
        $githubLink = $manager->getGithubLink();
        $data = [$expectedSalary, $experience, $githubLink];

        render($data);
    }
}

Good:

function showList(array $employees): void
{
    foreach ($employees as $employee) {
        $expectedSalary = $employee->calculateExpectedSalary();
        $experience = $employee->getExperience();
        $githubLink = $employee->getGithubLink();
        $data = [$expectedSalary, $experience, $githubLink];

        render($data);
    }
}

Very good:

It is better to use a compact version of the code.

function showList(array $employees): void
{
    foreach ($employees as $employee) {
        render([$employee->calculateExpectedSalary(), $employee->getExperience(), $employee->getGithubLink()]);
    }
}

⬆ back to top

Translations

This is also available in other languages:

⬆ back to top

clean-code-php's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

clean-code-php's Issues

Possibly incorrect: "Zero arguments is the ideal case"

In the section "Function arguments (2 or fewer ideally)" it says:
"Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided."
However, I think it's typically best to have at least 1 argument, as most functions with zero arguments aren't pure functions and aren't easily testable

Personally I prefer the wording in Clean Code JavaScript:
"One or two arguments is the ideal case, and three should be avoided if possible" (https://github.com/ryanmcdermott/clean-code-javascript#function-arguments-2-or-fewer-ideally)

Good practices are not following PSR Naming Convention

Good practice samples should follow PSR naming convention [http://www.php-fig.org/bylaws/psr-naming-conventions/], e.g. on Dependency Inversion Principle (DIP) good example, instead of

interface Employee
{
    public function work();
}

class Human implements Employee
{
    public function work()
    {
        // ....working
    }
}

class Robot implements Employee
{
    public function work()
    {
        //.... working much more
    }
}

class Manager
{
    private $employee;

    public function __construct(Employee $employee)
    {
        $this->employee = $employee;
    }

    public function manage()
    {
        $this->employee->work();
    }
}

it should be

interface EmployeeInterface
{
    public function work();
}

class Human implements EmployeeInterface
{
    public function work()
    {
        // ....working
    }
}

class Robot implements EmployeeInterface
{
    public function work()
    {
        //.... working much more
    }
}

class Manager
{
    private $employee;

    public function __construct(EmployeeInterface $employee)
    {
        $this->employee = $employee;
    }

    public function manage()
    {
        $this->employee->work();
    }
}

Disagree about: `Function arguments (2 or fewer ideally)`

I don't really believe that this is always a best practice.

IMHO the most of the cases are better to be explicit about all the dependencies needed by an object to be created, avoiding to created object in an invalid state.

Creating only valid object will reduce the amount of if ($object->getProperty() !== null) and will help you to better focus on the domain.

If the creation of an object is "hard" you can use a factory/builder to make it easier to interact with, but it will ALWAYS create an object in a valid state.

Don't write to global functions (classes?)

https://github.com/jupeter/clean-code-php#dont-write-to-global-functions

Could you explain please why you suggest class as a alternative of function in this case?
Why classes whouldn't conflict between each other like functions in that example?
And why namespaces and naming convenction wouldn't resolve this sort of issue?

I guess such kind of a solution would work fine as well:

use function \App\Helpers\config as myConfig; //just for instance
use function \Path\To\Imported\Package\config;

$app = new Application();

$app->setConfig(myConfig());
$app->setConfig(config());

"Bad" example for "Functions should do one thing" has a bug

https://github.com/jupeter/clean-code-php#functions-should-do-one-thing

Notice: Undefined variable: db on line 4

I can see 3 ways to fix it:

// OOP: it is a function of an object (a method)
function emailClients($clients) {
    foreach ($clients as $client) {
        $clientRecord = $this->db->find($client);
        if ($clientRecord->isActive()) {
            email($client);
        }
    }
}
// $db is passed as an argument
function emailClients($clients, $db) {
    foreach ($clients as $client) {
        $clientRecord = $db->find($client);
        if ($clientRecord->isActive()) {
            email($client);
        }
    }
}
// the function is a closure
$emailClients = function ($clients) use ($db) {
    foreach ($clients as $client) {
        $clientRecord = $db->find($client);
        if ($clientRecord->isActive()) {
            email($client);
        }
    }
};

See also #38

introduction of mocking on "Functions should only be one level of abstraction" should be removed

https://github.com/jupeter/clean-code-php#functions-should-only-be-one-level-of-abstraction

I think your refactoring results in two helper-classes "Lexer" and "Tokenizer". These types of classes should not be mocked nor handled by the di-framework.

Uncle Bob suggests to

Mock across architecturally significant boundaries, but not within those boundaries.

http://blog.cleancoder.com/uncle-bob/2014/05/10/WhenToMock.html

Avoid type-checking rule ignores union or intersection type

Avoid type-checking doesn't address a realistic situation in which one might do type checking. If type declaration can be used that's great, but often it's not the case.

One major issue that PHP doesn't support union or intersection types.

/**
 * @param \Traversable&\Countable $iterator
 * @return \Generator
 */
function iterator_chop(\Traversable $iterator): \Generator
{
    $piles = count($iterator); // Might not be countable
    // ....
}

Again in the second example

/**
 * @param int|float $val1
 * @param int|float $val2
 * @return int|float
 */
function combine($val1, $val2)
{
    return $val1 + $val2; // Are these numbers?
}

In the second case, it's likely for the code to work without an error as first, but result in an unexpected error or, event worst, an unexpected result later.

No type checking goes against the "Fail fast" principle, which prevents you having to chase bugs through the code.

While static code analysis does a good job, it doesn't capture all issues.

The argument about it being to verbose isn't that strong, as you have many solutions to write it as one line. For instance with beberlei/assert.

Incorrect code example in LSP

See Liskov substitution principle Good example:

abstract class Shape {
    private $width, $height; // should be protected, not private
    //...
}

class Rectangle extends Shape {
    public function __construct() {
        parent::__construct();
        $this->width = 0; // WRONG can't access $this->width as it's private access
        $this->height = 0; // WRONG can't access $this->height as it's private access
    }
    
    public function setWidth($width) {
        $this->width = $width; // same here
    }
    
    public function setHeight($height) {
        $this->height = $height; // same here
    }
    
    public function getArea() {
        return $this->width * $this->height; // same here
    }
}

$width and $height can't be accessed by Rectangle if private in Shape abstract class.

[Bad Example] Function names should say what they do

Function names should say what they do

Bad:

function addToDate(\DateTime $date, $month) {
    $date->modify(sprintf('+%d months', $month));
}

$date = new \DateTime();

// It's hard to to tell from the function name what is added
addToDate($date, 1);

Good:

function addMonthToDate($month, \DateTime $date) {
    $date->modify(sprintf('+%d months', $month));
}

$date = new \DateTime();
addMonthToDate(1, $date);

What is the purpose of addToDate()/addMonthToDate() functions?
What are they needed for?
These functions are meaningless.

Need help to understand the Avoid Conditionals section.

Love this repo! I have one issue that I just can't get my head around. https://github.com/jupeter/clean-code-php#avoid-conditionals

I get that its better to do the following (new AirForceOne())->getCruisingAltitude();.
However I still dont see the check to use AirForceOne over the 777.

Are you not just pushing that logic up higher then to a controller.

switch ($this->inputValue) {
    case '777':
        return (new Boeing777())->getCruisingAltitude();
    case 'Air Force One':
        return (new AirForceOne())->getCruisingAltitude();
    case 'Cessna':
        return (new Cessna())->getCruisingAltitude();
}

Not entirely clear example "Use the same vocabulary for the same type of variable"

https://github.com/jupeter/clean-code-php#use-the-same-vocabulary-for-the-same-type-of-variable

It's hard to quickly tell what is the subject of the issue here.
I don't see problem in class having methods like:

getUserInfo();
getClientData();

Because User and Client can be actually different entities.

I think it would be good to provide more description explaining that it refers to calling same Entity with different names, which should generally be avoided?

[WTF] Avoid Mental Mapping

Invalid "foreach" loop.

$locations = ['Austin', 'New York', 'San Francisco'];

foreach( $locations as $i=>$location ) {
// $location = $locations[$i];

doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch($location);

});

Arabic translation

thanks for your efforts, I suggest adding the Arabic version of this guide, and I'm ready to do the translation process and add it to the translations list.

[Bug] Use default arguments instead of short circuiting or conditionals

You broke your code.
https://github.com/jupeter/clean-code-php#use-default-arguments-instead-of-short-circuiting-or-conditionals

Original is good

function createMicrobrewery($name = null) {
    $breweryName = $name ?: 'Hipster Brew Co.';
    var_dump($breweryName);
}
createMicrobrewery();
createMicrobrewery('');
createMicrobrewery(null);
createMicrobrewery('foo');

Result

string(16) "Hipster Brew Co."
string(16) "Hipster Brew Co."
string(16) "Hipster Brew Co."
string(3) "foo"

Your "good"

function createMicrobrewery($breweryName = 'Hipster Brew Co.') {
    var_dump($breweryName);
}
createMicrobrewery();
createMicrobrewery('');
createMicrobrewery(null);
createMicrobrewery('foo');

Result

string(16) "Hipster Brew Co."
string(0) ""
NULL
string(3) "foo"

Result is different. You broke your code.

"Prefer composition over inheritance": Why you don't use traits?

You could really add a good multi-inheritance or composition example by mentioning threads. Although they may force a developer to jump into polimorphic tables, they are a great way to handle this.

I can't find an example of use of trait anywhere on your "clean-code-php" guide.

Interface Segregation Principle design flaw

In ISP there are severe design flaws which clearly indicate you have no experience with goverment employees:

class Human implements Employee
{
    public function work(): void
    {
        // ....working  --> instance would likely throw UnknownOperationException
    }

    public function eat(): void
    {
        // ...... eating in lunch break --> entire working hours IS-A lunch break; it may or may not have anything to do with eating
    }
}

Also, in Good: Not every worker is an employee, but every employee is a worker. --> Again, you have not met goverment employees.

All this makes it confusing to grasp the concept for some instances 😉

Comparison text

On the comparison example, the text currently reads -
The simple comparison will convert the string in an integer.

It would make more sense as -
The simple comparison will convert the string into an integer.

Phrases "withdraw balance" and "deposit balance" are nonsensical in English.

'Balance' as a noun is the name of the number representing the amount of money in your account. You cannot withdraw or deposit the actual number. You can however:

  • withdraw money
  • deposit money
  • increase balance (by depositing money)
  • decrease balance (by withdrawing money)

I'd just call the two functions withdraw() and deposit(). They're not ambiguous, as there's only one thing you can withdraw/deposit (money).

Function arguments (2 or fewer ideally)

Link to section.

A little strange.

In Bad example, the createMenu() function has 4 required dependencies ($title, $body, $buttonText, $cancellable).

In Good example, the createMenu() function has only 1 required dependency (MenuConfig).
But MenuConfig does not have required dependencies.
This means that we do not have guarantees that all the necessary dependencies will be in createMenu() function.

This means that the Good example does not solve the problems in the Bad example.

[WTF] Don't add unneeded context

https://github.com/jupeter/clean-code-php#dont-add-unneeded-context

What did you try to show in this code?

$car = [
    'carMake'  => 'Honda',
    'carModel' => 'Accord',
    'carColor' => 'Blue',
];

function paintCar(&$car) {
    $car['carColor'] = 'Red';
}

What relation has the name of the variable to the prefixes of the keys of the array?
Why do you change the array by reference?
Why do not you use classes to describe the structure?

Maybe you meant something like this:

class Car
{
    public $carMake;
    public $carModel;
    public $carColor;

    public function paint($color)
    {
        $this->carColor = $color;
    }
}

and

class Car
{
    public $make;
    public $model;
    public $color;

    public function paint($color)
    {
        $this->color = $color;
    }
}

Getters and setters leads to anemic domain model anti-pattern

Hello and thanks for your work, I'll share it !

There is an issue wih use getters and setters , mostly the "setter part". With entities, it leads to the anemic domain model anti-pattern. I think this article with php example from @beberlei explains it far better than I would.

The good news is that the example already seems correct : instead of having setters giving access to everything, there are mutators with explicit names : withdrawBalance and depositBalance, which already hold the logic to avoid negative balance. With simple getters/setters, this logic would be deported to another service, and nothing would prevent anyone from setting a negative balance anyway.

So, maybe we should only rename the title use getters and setters ?

EDIT : I did not suggest a new title. Maybe Use object encapsulation ? Change entities* state through explicit mutators ?

(* I say entities (or model) instead of object because some of them such as value objects should be immutable. Their public methods should only return a new instance with the new values instead of changing their state.)

Avoid conditionals GOOD example should be better :)

As you metion in section: Open/Closed Principle (OCP)

You should change the GOOD example in section Avoid conditionals like this:

interface Airplane
{
    public function getCruisingAltitude();
    // ...
}

class Boeing777 implements Airplane
{
    // ...

    public function getCruisingAltitude()
    {
        return $this->getMaxAltitude() - $this->getPassengerCount();
    }
}

class AirForceOne implements Airplane
{
    // ...

    public function getCruisingAltitude()
    {
        return $this->getMaxAltitude();
    }
}

class Cessna implements Airplane
{
    // ...

    public function getCruisingAltitude()
    {
        return $this->getMaxAltitude() - $this->getFuelExpenditure();
    }
}

Database Interface Layer concrete example

Does anyone have a or know of a concrete example of php code that would reflect "Clean Architecture" page 166 figure 17.1. I simply can wrap my head around it?

the attached code represents examples of what I have written so far, but I know this will not work for anything but a SQL database. In my example My use case is simple, I am trying to have a use log into the system. Please ignore my namespace names as I am trying to rework my code from a homemade "MVC" framework. Finally the view component was not included because it is trivial, it send a json string.

Thanks
ken

Login Code.zip

Define constants in those methods where you use, not globally

// Bad

class MyClass {
private const MY_CONSTANT = 5;

//
public function myFunction(): void
{

$myVar = self::MY_CONSTANT;

}

// Good idea? Let's check it out!

class MyClass {

public function myFunction(): void
{
$MY_CONSTANT = 5;
$myVar = $MY_CONSTANT;

}

reusable value-objects w/ better type safety

I didn't really understand the point of traits until recently and now I can't live without them. And since I didn't find anything about traits on here, I wanted to share my findings. Is this something you are interested in?


In this first example, the two arguments workEmail and personalEmail are switched. But according to the signature of updateEmail, everything is in order since both arguments are of type string:

final class User
{
    public function updateEmail(string $workEmail, string $personalEmail): void
    {
        /* ... */
    }
}

$user = new User();
$user->updateEmail('[email protected]', '[email protected]');

Here we created the value-object EmailTrait to wrap any email-value. But instead of a class, the value-object is a trait. We re-use the trait in WorkEmail and PersonalEmail. Both have the same behavior as EmailTrait but have their own type WorkEmail and PersonalEmail respectively.

trait EmailTrait
{
    private string $email;

    private function __construct(string $email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException(/* ... */);
        }

        $this->email = $email;
    }

    public static function fromString(string $email): self
    {
        return new self($email);
    }

    public function toString(): string
    {
        return $this->email;
    }
}

final class WorkEmail
{
    use EmailTrait;
}

final class PersonalEmail
{
    use EmailTrait;
}

Now in this second example, the signature of updateEmail is absolutely clear about its argument types and can't be misused:

final class User
{
    public function updateEmail(WorkEmail $work, PersonalEmail $personal): void
    {
        /* ... */
    }
}

$work = WorkEmail::fromString('[email protected]');
$personal = PersonalEmail::fromString('[email protected]');

$user = new User();
$user->updateEmail($work, $personal);

This is especially helpful, when there are a lot of primitive values that behave essentially the same, but represent different things in the domain (IDs, postal addresses, event-objects etc.).

Spoiler tag

Maybe we should use spoilers for examples?
This is just an idea.


Avoid conditionals

This seems like an impossible task. Upon first hearing this, most people say,
"how am I supposed to do anything without an if statement?" The answer is that
you can use polymorphism to achieve the same task in many cases. The second
question is usually, "well that's great but why would I want to do that?" The
answer is a previous clean code concept we learned: a function should only do
one thing. When you have classes and functions that have if statements, you
are telling your user that your function does more than one thing. Remember,
just do one thing.

Bad:
class Airplane
{
    // ...

    public function getCruisingAltitude()
    {
        switch ($this->type) {
            case '777':
                return $this->getMaxAltitude() - $this->getPassengerCount();
            case 'Air Force One':
                return $this->getMaxAltitude();
            case 'Cessna':
                return $this->getMaxAltitude() - $this->getFuelExpenditure();
        }
    }
}
Good:
interface Airplane
{
    // ...

    public function getCruisingAltitude();
}

class Boeing777 implements Airplane
{
    // ...

    public function getCruisingAltitude()
    {
        return $this->getMaxAltitude() - $this->getPassengerCount();
    }
}

class AirForceOne implements Airplane
{
    // ...

    public function getCruisingAltitude()
    {
        return $this->getMaxAltitude();
    }
}

class Cessna implements Airplane
{
    // ...

    public function getCruisingAltitude()
    {
        return $this->getMaxAltitude() - $this->getFuelExpenditure();
    }
}

I offer this only because the document is very large.

There is another solution.
Move sections to separate files.

├ README.md
├ variables
│ ├ use-meaningful-and-pronounceable-variable-names.md
│ ├ use-the-same-vocabulary-for-the-same-type-of-variable.md
│ ├ ...
│ └ use-default-arguments-instead-of-short-circuiting-or-conditionals.md
├ ...
├ solid
│ ├ srp.md
│ ├ ocp.md
│ ├ lsp.md
│ ├ isp.md
│ └ dip.md
├ dry.md
└ translations.md

This will make it possible to use a more detailed description for each example.
Yet again. It's just an idea.

LSP ambiguous example

In the comment for Liskov Substitution Principle bad example :

function renderLargeRectangles(Rectangle $rectangles): void
{
    foreach ($rectangles as $rectangle) {
        $rectangle->setWidth(4);
        $rectangle->setHeight(5);
        $area = $rectangle->getArea(); // BAD: Will return 25 for Square. Should be 20.
        $rectangle->render($area);
    }
}

$rectangles = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles($rectangles);

For a square the math is right as getArea() should return 25, not 20.
I understand that it implies 20 for 4x5, but this is only for not square and Square is explicitely used.
The example and comment "Should be 20" are confusing.

Edit :
Additionnaly, if the height/width/length are in constructor as seen in acf92a1 and not defined in a function.
You then have :

function renderLargeRectangles(Rectangle $rectangles): void
{
    foreach ($rectangles as $rectangle) {
        $area = $rectangle->getArea(); // GOOD: Will return 25 for Square.
        $rectangle->render($area);
    }
}

$rectangles = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];
renderLargeRectangles($rectangles);

And the example becomes correct but I'm being fussy.

Variable name mismatch

Hi,
There is a slight mismatch between declaration and usage of $matches in "Use explanatory variables"

preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matchers['city'], $matchers['zipCode']);
preg_match($cityZipCodeRegex, $address, $matches);
list(, $city, $zipCode) = $matchers;

"Make objects have private/protected members" section should be improved

This section doesn't provide any useful explanation when and why to use public, private and protected access modifiers.

Consider adding explanation that

  1. public methods and properties are most dangerous for changes, because some outside code may easily rely on them and you can't control what code relies on them. Modifications in class are dangerous for all users of class.
  2. protected methods are as dangerous as public, because they are available in scope of any child class. This effectively means that difference between public and protected is only in access mechanism, but encapsulation guarantee is the same (3rd party developers are affected). Modifications in class are dangerous for all descendant classes.
  3. private methods are your safe harbor in this doubtful world. They guarantee you that code in your methods is dangerous to modify only in boundaries of single class (which means that when you have tests for your protected/public methods that cover all calls of your private method, and as long as you don't do magic, like side effects or usage of global state, you are safe for modifications and you won't have Jenga effect).

Therefore, use private by default and public/protected when you need to provide access.

There is also one modern trend that I discovered. People, who practice TDD and cover 100% LOC with tests, usually end up with almost 0 private methods, because private methods are hard to test. Encapsulation is then usually guaranteed by usage of shim classes.

This leads to good thing - implementation can be replaced with more performant/maintainable/flexible/better class easier; but this also leads to bad thing - people try to create very thin layers of functionality, like 100 classes of 10 LOC, and every such class performs a single for loop or a single call to real class, with usually too technical name and too thin focus.

Instead, it is better to hide your implementation behind private method first and when it has grown too much (e.g. dependencies for class with private method have grown too much, or LOC are too many) or when you require more flexibility, or you start seeing that it is starting to have different focus than original class - don't hesitate to extract it to separate class.

Discussion about "Don't add unneeded context"

Hi,
I would like to bring up a discussion about "Don't add unneeded context". I have few considerations why I think this very example is not good and the context is not unneeded. On the contrary - on ActiveRecord classes it is improves greatly searchability, traceability and prevents hard to detect bugs:

  • I find extremely useful the properties to be named the same way for the sake of traceability from the front end (field names in forms) all the way back to the database column names
  • because of the above not having a prefix and having just column names like "color", or "name" (think of user_name, role_name, bank_name) and having of join of three tables like "users", "roles", "bank" and forgetting to set aliases will produce wrong results. The last selected table will overwrite the names of the rest. Consider having not just three tables but a join of 10 or even more... with tens of columns each... It is a lot of typing to alias many things. And if there is: SELECT users.*, roles.* ... then things go really bad. When there are hundreds of returned columns overwritten values go unnoticed.
  • In regards to the front end - in a form where in one go (read one transaction) we need to create a User and a Role we will need to add prefixes to avoid collision of the "names" (role_name vs user_name).
  • Searchability - if I need to find out where the user name is used I can search for "user_name" while if I dont have the prefix I will need to search for "->name" which will return also Roles objects, Banks objects... The object may or may not be named "$user" in order to make a search "user->name". Also this way it can be searched in SQL queries, frontend...

I would love to hear your opinion on that.
Thank you

Wrong class declaration

There is a class in your code with:

class menuConfig() {
...
}

You should remove ()

Also, there is a guide called "php the right way" check it out

Why do not you use PHP >=7.1 right away in examples?

I understand that many developers are still using PHP 5 but it would be nice to have all the examples written in PHP 7.1 (to use, among other things, strict types), especially taking into an account that PHP 5.6 has no active support anymore, just the security updates.

Question on coupling of static classes

I recently stumbled across a problem applying the Dependency Inversion Principle (DIP) trying to write classes for communication with either local (fopen()) or remote (fsockopen()) serial ports. (In the following example I'll stick to the Tcp class using fsockopen() and leave out the interfaces.)

<?php
namespace Gregor\ExampleSrc;

final class Socket implements SocketFunctionsInterface
{
    public static function fsockopen($hostname, $port, &$errno, &$errstr, $timeout): ?SocketFunctionsInterface
    {
        $socket = fsockopen($hostname, $port, $errno, $errstr, $timeout);
        if (is_resource($socket)) {
            return new self($socket);
        }
        return null;
    }

    /**
     * @var resource
     */
    private $socket;

    public function __construct($socket)
    {
        $this->socket = $socket;
    }

    public function __destruct()
    {
        fclose($this->socket);
        $this->socket = null;
    }

    public function fwrite($string, $length)
    {
        return fwrite($this->socket, $string, $length);
    }

    public function fgetc()
    {
        return fgetc($this->socket);
    }
}
<?php
namespace Gregor\ExampleSrc;

final class Tcp implements CommunicationInterface
{
    /**
     * @var SocketFunctionsInterface
     */
    private $socket;

    /**
     * @var SocketFunctionsInterface
     */
    private static $socketClass = Socket::class;

    public function __construct(string $host, int $port)
    {
        //... code preparing the class, that needs to be tested
        $socketClass = self::$socketClass;
        while (($this->socket = $socketClass::fsockopen($host, $port, $errNo, $errMessage, $timeout)) === null) {
            //... lots of code, that needs to be tested
        }
    }

    public static function setSocketFunctionsClass(string $className): void
    {
        $class = new ReflectionClass($className);
        if (!$class->implementsInterface(SocketFunctionsInterface::class)) {
            throw new InvalidConfigException(sprintf(
                'The given class %s doesn\'t implement %s!',
                $className,
                SocketFunctionsInterface::class
            ));
        }
        self::$socketClass = $className;
    }

    //... code using $this->socket->... methods, that needs to be tested
}

In order to test the code of the Tcp class, I moved fsockopen() fgetc() and frwite() into a separate class Socket. Socket mustn't contain any code, that would need testing. However, in order to create an instance of that Socket class, fsockopen() needs to be called and that can't be done outside of the Tcp class.

My concern is:
The case of injecting a static class before the constructor is called, in this case self::$socketClass, is not covered by DIP. The solution above doesn't look clean to me.

What can I do?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.