forked from piotrplenik/clean-code-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.md
2209 lines (1687 loc) · 50.1 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Clean Code PHP
## Table of Contents
1. [Introduction](#introduction)
2. [Variables](#variables)
* [Use meaningful and pronounceable variable names](#use-meaningful-and-pronounceable-variable-names)
* [Use the same vocabulary for the same type of variable](#use-the-same-vocabulary-for-the-same-type-of-variable)
* [Use searchable names (part 1)](#use-searchable-names-part-1)
* [Use searchable names (part 2)](#use-searchable-names-part-2)
* [Use explanatory variables](#use-explanatory-variables)
* [Avoid nesting too deeply and return early (part 1)](#avoid-nesting-too-deeply-and-return-early-part-1)
* [Avoid nesting too deeply and return early (part 2)](#avoid-nesting-too-deeply-and-return-early-part-2)
* [Avoid Mental Mapping](#avoid-mental-mapping)
* [Don't add unneeded context](#dont-add-unneeded-context)
3. [Comparison](#comparison)
* [Use identical comparison](#use-identical-comparison)
* [Null coalescing operator](#null-coalescing-operator)
4. [Functions](#functions)
* [Use default arguments instead of short circuiting or conditionals](#use-default-arguments-instead-of-short-circuiting-or-conditionals)
* [Function arguments (2 or fewer ideally)](#function-arguments-2-or-fewer-ideally)
* [Function names should say what they do](#function-names-should-say-what-they-do)
* [Functions should only be one level of abstraction](#functions-should-only-be-one-level-of-abstraction)
* [Don't use flags as function parameters](#dont-use-flags-as-function-parameters)
* [Avoid Side Effects](#avoid-side-effects)
* [Don't write to global functions](#dont-write-to-global-functions)
* [Don't use a Singleton pattern](#dont-use-a-singleton-pattern)
* [Encapsulate conditionals](#encapsulate-conditionals)
* [Avoid negative conditionals](#avoid-negative-conditionals)
* [Avoid conditionals](#avoid-conditionals)
* [Avoid type-checking (part 1)](#avoid-type-checking-part-1)
* [Avoid type-checking (part 2)](#avoid-type-checking-part-2)
* [Remove dead code](#remove-dead-code)
5. [Objects and Data Structures](#objects-and-data-structures)
* [Use object encapsulation](#use-object-encapsulation)
* [Make objects have private/protected members](#make-objects-have-privateprotected-members)
6. [Classes](#classes)
* [Prefer composition over inheritance](#prefer-composition-over-inheritance)
* [Avoid fluent interfaces](#avoid-fluent-interfaces)
* [Prefer final classes](#prefer-final-classes)
7. [SOLID](#solid)
* [Single Responsibility Principle (SRP)](#single-responsibility-principle-srp)
* [Open/Closed Principle (OCP)](#openclosed-principle-ocp)
* [Liskov Substitution Principle (LSP)](#liskov-substitution-principle-lsp)
* [Interface Segregation Principle (ISP)](#interface-segregation-principle-isp)
* [Dependency Inversion Principle (DIP)](#dependency-inversion-principle-dip)
8. [Don’t repeat yourself (DRY)](#dont-repeat-yourself-dry)
9. [Translations](#translations)
## Introduction
Software engineering principles, from Robert C. Martin's book
[*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882),
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](https://github.com/ryanmcdermott/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:**
```php
$ymdstr = $moment->format('y-m-d');
```
**Good:**
```php
$currentDate = $moment->format('y-m-d');
```
**[⬆ back to top](#table-of-contents)**
### Use the same vocabulary for the same type of variable
**Bad:**
```php
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();
```
**Good:**
```php
getUser();
```
**[⬆ back to top](#table-of-contents)**
### 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:**
```php
// What the heck is 448 for?
$result = $serializer->serialize($data, 448);
```
**Good:**
```php
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
```
### Use searchable names (part 2)
**Bad:**
```php
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:**
```php
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](#table-of-contents)**
### Use explanatory variables
**Bad:**
```php
$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.
```php
$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.
```php
$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](#table-of-contents)**
### 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:**
```php
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:**
```php
function isShopOpen(string $day): bool
{
if (empty($day)) {
return false;
}
$openingDays = ['friday', 'saturday', 'sunday'];
return in_array(strtolower($day), $openingDays, true);
}
```
**[⬆ back to top](#table-of-contents)**
### Avoid nesting too deeply and return early (part 2)
**Bad:**
```php
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:**
```php
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](#table-of-contents)**
### Avoid Mental Mapping
Don’t force the reader of your code to translate what the variable means.
Explicit is better than implicit.
**Bad:**
```php
$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:**
```php
$locations = ['Austin', 'New York', 'San Francisco'];
foreach ($locations as $location) {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch($location);
}
```
**[⬆ back to top](#table-of-contents)**
### Don't add unneeded context
If your class/object name tells you something, don't repeat that in your
variable name.
**Bad:**
```php
class Car
{
public $carMake;
public $carModel;
public $carColor;
//...
}
```
**Good:**
```php
class Car
{
public $make;
public $model;
public $color;
//...
}
```
**[⬆ back to top](#table-of-contents)**
## Comparison
### Use [identical comparison](http://php.net/manual/en/language.operators.comparison.php)
**Not good:**
The simple comparison will convert the string into an integer.
```php
$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.
```php
$a = '42';
$b = 42;
if ($a !== $b) {
// The expression is verified
}
```
The comparison `$a !== $b` returns `TRUE`.
**[⬆ back to top](#table-of-contents)**
### Null coalescing operator
Null coalescing is a new operator [introduced in PHP 7](https://www.php.net/manual/en/migration70.new-features.php). 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:**
```php
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
```
**Good:**
```php
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';
```
**[⬆ back to top](#table-of-contents)**
## Functions
### Use default arguments instead of short circuiting or conditionals
**Not good:**
This is not good because `$breweryName` can be `NULL`.
```php
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.
```php
function createMicrobrewery($name = null): void
{
$breweryName = $name ?: 'Hipster Brew Co.';
// ...
}
```
**Good:**
You can use [type hinting](https://www.php.net/manual/en/language.types.declarations.php) and be sure that the `$breweryName` will not be `NULL`.
```php
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
// ...
}
```
**[⬆ back to top](#table-of-contents)**
### 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:**
```php
class Questionnaire
{
public function __construct(
string $firstname,
string $lastname,
string $patronymic,
string $region,
string $district,
string $city,
string $phone,
string $email
) {
// ...
}
}
```
**Good:**
```php
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](#table-of-contents)**
### Function names should say what they do
**Bad:**
```php
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:**
```php
class Email
{
//...
public function send(): void
{
mail($this->to, $this->subject, $this->body);
}
}
$message = new Email(...);
// Clear and obvious
$message->send();
```
**[⬆ back to top](#table-of-contents)**
### 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:**
```php
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.
```php
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.
```php
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](#table-of-contents)**
### 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:**
```php
function createFile(string $name, bool $temp = false): void
{
if ($temp) {
touch('./temp/' . $name);
} else {
touch($name);
}
}
```
**Good:**
```php
function createFile(string $name): void
{
touch($name);
}
function createTempFile(string $name): void
{
touch('./temp/' . $name);
}
```
**[⬆ back to top](#table-of-contents)**
### 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:**
```php
// 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:**
```php
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](#table-of-contents)**
### 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:**
```php
function config(): array
{
return [
'foo' => 'bar',
];
}
```
**Good:**
```php
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
```php
$configuration = new Configuration([
'foo' => 'bar',
]);
```
And now you must use instance of `Configuration` in your application.
**[⬆ back to top](#table-of-contents)**
### Don't use a Singleton pattern
Singleton is an [anti-pattern](https://en.wikipedia.org/wiki/Singleton_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](https://en.wikipedia.org/wiki/Code_smell).
2. They violate the [single responsibility principle](#single-responsibility-principle-srp): by virtue of the fact that **they control their own creation and lifecycle**.
3. They inherently cause code to be tightly [coupled](https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29). 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](http://misko.hevery.com/about/) about the [root of problem](http://misko.hevery.com/2008/08/25/root-cause-of-singletons/).
**Bad:**
```php
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:**
```php
class DBConnection
{
public function __construct(string $dsn)
{
// ...
}
// ...
}
```
Create instance of `DBConnection` class and configure it with [DSN](http://php.net/manual/en/pdo.construct.php#refsect1-pdo.construct-parameters).
```php
$connection = new DBConnection($dsn);
```
And now you must use instance of `DBConnection` in your application.
**[⬆ back to top](#table-of-contents)**
### Encapsulate conditionals
**Bad:**
```php
if ($article->state === 'published') {
// ...
}
```
**Good:**
```php
if ($article->isPublished()) {
// ...
}
```
**[⬆ back to top](#table-of-contents)**
### Avoid negative conditionals
**Bad:**
```php
function isDOMNodeNotPresent(DOMNode $node): bool
{
// ...
}
if (! isDOMNodeNotPresent($node)) {
// ...
}
```
**Good:**
```php
function isDOMNodePresent(DOMNode $node): bool
{
// ...
}
if (isDOMNodePresent($node)) {
// ...
}
```
**[⬆ back to top](#table-of-contents)**
### 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