forked from piotrplenik/clean-code-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.md
2276 lines (1682 loc) · 56.7 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
# PHP Toza Kod
## Mundarija
1. [Kirish](#kirish)
2. [O'zgaruvchilar](#ozgaruvchilar)
- [Ma'noga ega va tushunarli nomlardan foydalaning](#manoga-ega-va-tushunarli-nomlardan-foydalaning)
- [Bir xil turdagi o'zgaruvchilar uchun xuddi shunday nomdan foydalaning](#bir-xil-turdagi-ozgaruvchilar-uchun-xuddi-shunday-nomdan-foydalaning)
- [Izlashga qulay bo'lgan nomlardan foydalaning (1-qism)](#izlashga-qulay-bolgan-nomlardan-foydalaning-1-qism)
- [Izlashga qulay bo'lgan nomlardan foydalaning (2-qism)](#izlashga-qulay-bolgan-nomlardan-foydalaning-2-qism)
- [Mantiqni izohlaydigan o'zgaruvchilardan foydalaning](#mantiqni-izohlaydigan-ozgaruvchilardan-foydalaning)
- [Shart operatorlarini bir birini ichiga chuqur joylashtirish va qiymatlarni erta qaytarishni oldini oling (1-qism)](#shart-operatorlarini-bir-birini-ichiga-chuqur-joylashtirish-va-qiymatlarni-erta-qaytarishni-oldini-oling-1-qism)
- [Shart operatorlarini bir birini ichiga chuqur joylashtirish va qiymatlarni erta qaytarishni oldini oling (2-qism)](#shart-operatorlarini-bir-birini-ichiga-chuqur-joylashtirish-va-qiymatlarni-erta-qaytarishni-oldini-oling-2-qism)
- [O'zgaruvchilarni nomlashda Aqliy Xaritalamang](#ozgaruvchilarni-nomlashda-aqliy-xaritalamang)
- [Keraksiz kontekst qo'shmang](#keraksiz-kontekst-qoshmang)
- [Qisqa formalar yoki shartlar o'rniga standart argumentlardan foydalaning](#qisqa-formalar-yoki-shartlar-orniga-standart-argumentlardan-foydalaning)
3. [Taqqsolash](#taqqoslash)
- [Toifa bilan taqqoslash'dan foydalaning](#toifa-bilan-taqqoslashdan-foydalaning)
- [Null birlashma operatori](#null-birlashma-operatori)
4. [Funksiyalar](#funksiyalar)
- [Funksiya argumentlari (2 yoki kamrog'i ideal)](#funksiya-argumentlari-2-yoki-kamrogi-ideal)
- [Funksiya nomi qanday amal bajarilayotganini aytishi kerak](#funksiya-nomi-qanday-amal-bajarilayotganini-aytishi-kerak)
- [Funksiyalar bir darajada abstrakt bo'lishi kerak](#funksiyalar-bir-darajada-abstrakt-bolishi-kerak)
- [Funksiyada mantiqiy toifalardan parametr sifatida foydalanmang](#funksiyada-mantiqiy-toifalardan-parametr-sifatida-foydalanmang)
- [Yondosh ta'sirlarni oldini oling](#yondosh-tasirlarni-oldini-oling)
- [Global funksiyalarga yozmang](#global-funksiyalarga-yozmang)
- [Singleton pattern'dan foydalanmang](#singleton-patterndan-foydalanmang)
- [Shartlarni inkapsulatsiyalash](#shartlarni-inkapsulatsiyalash)
- [Inkor qiluvchi shartlardan foydalanmang](#inkor-qiluvchi-shartlardan-foydalanmang)
- [Shartlarni oldini oling](#shartlarni-oldini-oling)
- [Toifani tekshirishni oldini oling (1-qism)](#toifani-tekshirishni-oldini-oling-1-qism)
- [Toifani tekshirishni oldini oling (2-qism)](#toifani-tekshirishni-oldini-oling-2-qism)
- [O'lik kodni olib tashlang](#olik-kodni-olib-tashlang)
5. [Obyektlar va ma'lumotlar tuzilmasi](#obyektlar-va-malumotlar-tuzilmasi)
- [Obyektni inkapsulatsiyalashdan foydalaning](#obyektni-inkapsulatsiyalashdan-foydalaning)
- [Obyektlarni private/protected xususiyatli qiling](#obyektlarni-private-protected-xususiyatli-qiling)
6. [Sinflar](#sinflar)
- [Meros olishdan ko'ra kompozitsiyani tanlang](#meros-olishdan-kora-kompozitsiyani-tanlang)
- [Fluent interfeyslardan saqlaning](#fluent-interfeyslardan-saqlaning)
- [Final sinflardan foydalaning](#final-sinflardan-foydalaning)
7. [SOLID](#solid)
- [Yagona javobgarlik printspi (Single Responsibility Principle, SRP)](#yagona-javobgarlik-printspi-single-responsibility-principle-srp)
- [Ochiq/Yopiqlik printspi (Open/Closed Principle, OCP)](#ochiq-yopiqlik-printspi-open-closed-principle-ocp)
- [Liskov almashtirish printsipi (Liskov Substitution Principle, LSP)](#liskov-almashtirish-printsipi-liskov-substitution-principle-lsp)
- [Interfeysni ajratish printsipi (Interface Segregation Principle, ISP)](#interfeysni-ajratish-printsipi-interface-segregation-principle-isp)
- [Bog'liqlik inversiyasi printsipi (Dependency Inversion Principle, DIP)](#bog-liqlik-inversiyasi-printsipi-dependency-inversion-principle-dip)
8. [O'zingizni takrorlamang (Don’t repeat yourself, DRY)](#ozingizni-takrorlamang-dont-repeat-yourself-dry)
9. [Tarjimalar](#tarjimalar)
## Kirish
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+.
## O'zgaruvchilar
### Ma'noga ega va tushunarli nomlardan foydalaning
**Yomon:**
```php
declare(strict_types=1);
$ymdstr = $moment->format('y-m-d');
```
**Yaxshi:**
```php
declare(strict_types=1);
$currentDate = $moment->format('y-m-d');
```
**[⬆ boshiga qaytish](#mundarija)**
### Bir xil turdagi o'zgaruvchilar uchun xuddi shunday nomdan foydalaning
**Yomon:**
```php
declare(strict_types=1);
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();
```
**Yaxshi:**
```php
declare(strict_types=1);
getUser();
```
**[⬆ boshiga qaytish](#mundarija)**
### Izlashga qulay bo'lgan nomlardan foydalaning (1-qism)
Biz kod yozishdan ko'ra ko'proq ularni o'qiymiz. Shuning uchun biz yozadigan kod izlashga va o'qishga qulay bo'lishi
muhimdir. Dasturimizni tushunishda ahamaiyatga ega bo'lgan o'zgaruvchilarni ma'noli qilib nomlamaslik, kodni o'qiyotgan
dasturchiga qiyinchilik tug'diradi. O'zgaruvchilarni izlashga qulay qilib nomlang.
**Yomon:**
```php
declare(strict_types=1);
// 448 nimani anglatadi?
$result = $serializer->serialize($data, 448);
```
**Yaxshi:**
```php
declare(strict_types=1);
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
```
### Izlashga qulay bo'lgan nomlardan foydalaning (2-qism)
**Yomon:**
```php
declare(strict_types=1);
class User
{
// 7 nimani anglatadi ?
public $access = 7;
}
// 4 nimani anglatadi?
if ($user->access & 4) {
// ...
}
// By yerda qanday mantiq ketayorgani vaqti kelib o'zingizni ham yodingizdan ko'tariladi
$user->access ^= 2;
```
**Yaxshi:**
```php
declare(strict_types=1);
class User
{
public const ACCESS_READ = 1;
public const ACCESS_CREATE = 2;
public const ACCESS_UPDATE = 4;
public const ACCESS_DELETE = 8;
// Bu yerda esa hammasi tushunarli. Boshlang'ich holatda `$access`ga o'qish, tahrirlash va yaratish huquqlari o'zlashtirilmoqda.
public $access = self::ACCESS_READ | self::ACCESS_CREATE | self::ACCESS_UPDATE;
}
if ($user->access & User::ACCESS_UPDATE) {
// tahrirlash ...
}
// Nimadir yaratishga bo'lgan huquqni cheklash
$user->access ^= User::ACCESS_CREATE;
```
**[⬆ boshiga qaytish](#mundarija)**
### Mantiqni izohlaydigan o'zgaruvchilardan foydalaning
**Yomon:**
```php
declare(strict_types=1);
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches[1], $matches[2]);
```
**Yomon emas:**
Bu yaxshiroq, lekin biz haliham to'liq mantiqni tushunish uchun regex'ga bog'liqmiz.
```php
declare(strict_types=1);
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
[, $city, $zipCode] = $matches;
saveCityZipCode($city, $zipCode);
```
**Yaxshi:**
Subpattern'larni nomlash orqali regex'ga bog'liqligimizni kamaytirdik.
```php
declare(strict_types=1);
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches['city'], $matches['zipCode']);
```
**[⬆ boshiga qaytish](#mundarija)**
### Shart operatorlarini bir birini ichiga chuqur joylashtirish va qiymatlarni erta qaytarishni oldini oling (1-qism)
Juda ham ko'p if-else operatorlari kodingizni tushunishni qiyinlashtiradi. Aniqlik mujmallikdan ko'ra yaxshiroq.
**Yomon:**
```php
declare(strict_types=1);
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;
}
```
**Yaxshi:**
```php
declare(strict_types=1);
function isShopOpen(string $day): bool
{
if (empty($day)) {
return false;
}
$openingDays = ['friday', 'saturday', 'sunday'];
return in_array(strtolower($day), $openingDays, true);
}
```
**[⬆ boshiga qaytish](#mundarija)**
### Shart operatorlarini bir birini ichiga chuqur joylashtirish va qiymatlarni erta qaytarishni oldini oling (2-qism)
**Yomon:**
```php
declare(strict_types=1);
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';
}
```
**Yaxshi:**
```php
declare(strict_types=1);
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);
}
```
**[⬆ boshiga qaytish](#mundarija)**
### O'zgaruvchilarni nomlashda Aqliy Xaritalamang
Kodingiz o'quvchisini o'zgaruvchi nimani anglatishini tarjima qilishiga majburlamang. Aniqlik mujmallikdan ko'ra
yaxshiroq.
**Yomon:**
```php
$l = ['Austin', 'New York', 'San Francisco'];
for ($i = 0; $i < count($l); $i++) {
$li = $l[$i];
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Shoshmang, `$li` nima bo'ldi bu yana?
dispatch($li);
}
```
**Yaxshi:**
```php
declare(strict_types=1);
$locations = ['Austin', 'New York', 'San Francisco'];
foreach ($locations as $location) {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch($location);
}
```
**[⬆ boshiga qaytish](#mundarija)**
### Keraksiz kontekst qo'shmang
Agar class/obyekt'ingizni nomi nimanidir anglatib turgan bo'lsa, o'zgaruvchingizni nomida uni takrorlamang
**Yomon:**
```php
declare(strict_types=1);
class Car
{
public $carMake;
public $carModel;
public $carColor;
//...
}
```
**Yaxshi:**
```php
declare(strict_types=1);
class Car
{
public $make;
public $model;
public $color;
//...
}
```
**[⬆ boshiga qaytish](#mundarija)**
### Qisqa formalar yoki shartlar o'rniga standart argumentlardan foydalaning
**Yaxshi emas:**
Bu yaxshi emas chunki `$breweryName` ning qiymati `NULL` bo'lishi mumkin.
```php
function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
{
// ...
}
```
**Yomon emas:**
Bu variant oldingisiga qaraganda ancha tushunarli, ammo u o'zgaruvchining qiymatini yaxshiroq boshqaradi.
```php
function createMicrobrewery($name = null): void
{
$breweryName = $name ?: 'Hipster Brew Co.';
// ...
}
```
**Yaxshi:**
[Toifalarni boshqarish](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) dan
foydalanishingiz mumkin va `$breweryName` ning qiymati `NULL` ga teng bo'lmasligiga ishonchingiz komil bo'ladi.
```php
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
// ...
}
```
**[⬆ boshiga qaytish](#mundarija)**
## Taqqoslash
### [Toifa bilan taqqoslash](http://php.net/manual/en/language.operators.comparison.php)dan foydalaning
**Yaxshi emas:**
Oddiy taqqoslash satrni butun songa aylantiradi.
```php
declare(strict_types=1);
$a = '42';
$b = 42;
if ($a != $b) {
// Ifoda bajarilmaydi
}
```
`$a != $b` ifodasi `FALSE` (yolg'on) qiymat qaytaradi, aslide esa `TRUE` (rost) qaytarishi kerak. Chunki, satr
toifasidagi `42` butun toifadagi `42` dan farq qiladi.
**Yaxshi:**
Toifa bilan taqqoslaganda o'zgaruvchilarning qiymati bilan birgalikda toifasi ham solishtiriladi.
```php
declare(strict_types=1);
$a = '42';
$b = 42;
if ($a !== $b) {
// Ifoda bajariladi
}
```
`$a !== $b` taqqosi `TRUE` (rost) qiymat qaytaradi.
**[⬆ boshiga qaytish](#mundarija)**
### Null birlashma operatori
Null birlashma operatori [PHP 7](https://www.php.net/manual/en/migration70.new-features.php) versiyadan boshlab joriy
qilingan yangi operator hisoblanadi. Bu operator ternar `isset ()` bilan birgalikda ishlatish kerak bo'lgan oddiy holat
uchun sintaktik qisqartma sifatida qo'shilgan. Bu operator dastlabki operanda mavjud bo'lsa va u `null` ga teng bo'lmasa
shu operandani qaytaradi, aks holda keyingi operandani qaytaradi;
**Yomon:**
```php
declare(strict_types=1);
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
```
**Yaxshi:**
```php
declare(strict_types=1);
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';
```
**[⬆ boshiga qaytish](#mundarija)**
## Funksiyalar
### Funksiya argumentlari (2 yoki kamrog'i ideal)
Funksiya qabul qiluvchi parametrlarini cheklash juda muhimdir, chunki bu testlash jarayonini osonlashtiradi. Uchtadan
ortiq parametrlarni qabul qilish har bir holatni testlayotgan paytingizda ko'plab qiyinchiliklarni yuzaga keltiradi.
Argumentsiz funksiyalar bu ideal holatdir. Bir yoki ikkita argument qabul qilish yaxshi, uchtadan esa qochgan ma'qul.
Bundan boshqa holatlarda esa imkon qadar birlashtirish kerak. Odatda, agar sizda 2 tadan ortiq argument bo'lsa u holda
sizning funksiyangiz juda ko'p amalni bajarishga harakat qiladi. Bunday bo'lmagan hollarda esa argumentlarni obyektlarga
joylashtiring.
**Yomon:**
```php
declare(strict_types=1);
class Questionnaire
{
public function __construct(
string $firstname,
string $lastname,
string $patronymic,
string $region,
string $district,
string $city,
string $phone,
string $email
) {
// ...
}
}
```
**Yaxshi:**
```php
declare(strict_types=1);
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)
{
// ...
}
}
```
**[⬆ boshiga qaytish](#mundarija)**
### Funksiya nomi qanday amal bajarilayotganini aytishi kerak
**Yomon:**
```php
class Email
{
//...
public function handle(): void
{
mail($this->to, $this->subject, $this->body);
}
}
$message = new Email(...);
// Nima bu ? Hozir biz faylga yozayapmizmi ?
$message->handle();
```
**Yaxshi:**
```php
class Email
{
//...
public function send(): void
{
mail($this->to, $this->subject, $this->body);
}
}
$message = new Email(...);
// Tushunarli va aniq
$message->send();
```
**[⬆ boshiga qaytish](#mundarija)**
### Funksiyalar bir darajada abstrakt bo'lishi kerak
Sizda bir darajadan ortiq abstraktsiya bo'lganida funksiyangiz odatada ko'p ishlaydi. Funksiyalarni ajratish qayta
foydalanuvchanlikni yaxshilaydi va testlashni osonlashtiradi.
**Yomon:**
```php
declare(strict_types=1);
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...
}
}
```
**Yaxshi emas:**
Biz biroz funksionnalikni amalga oshirdik, lekin `parseBetterPHPAlternative()` funksiyasi haliham testlab bo'lmaydigan
darajada juda murakkab.
```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...
}
}
```
**Yaxshi:**
Eng yaxshi yechim bu `parseBetterPHPAlternative()` funksiyasini bog'liqligini ko'chirish.
```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...
}
}
}
```
**[⬆ boshiga qaytish](#mundarija)**
### Funksiyada mantiqiy toifalardan parametr sifatida foydalanmang
Mantiqiy operatorlar foydalanuvchiga funksiya bir nechta amal bajarishini bildiradi. Funksiya bitta amalni bajraishi
kerak. Agar funksiya mantiqiy asosga ko'ra turli xil amllarni bajarishi kerak bo'lsa, uni ajrating.
**Yomon:**
```php
declare(strict_types=1);
function createFile(string $name, bool $temp = false): void
{
if ($temp) {
touch('./temp/' . $name);
} else {
touch($name);
}
}
```
**Yaxshi:**
```php
declare(strict_types=1);
function createFile(string $name): void
{
touch($name);
}
function createTempFile(string $name): void
{
touch('./temp/' . $name);
}
```
**[⬆ boshiga qaytish](#mundarija)**
### Yondosh ta'sirlarni oldini oling
Agar funksiya qabul qilgan qiymatidan tashqari amal bajarsa va boshqa bir qiymat yoki qiymatlarni qaytarsa, yon ta'sirni
yuzaga keltiradi. Yon ta'sirlar faylga yozish, ba'zi global o'zgaruvchilarni o'zgartirish yoki tasodifan barcha
pullaringizni begonaga o'takib yuborish kabilar bo'lishi mumkin.
Masalan, ba'zida dasturda yon ta'sirlarga ega bo'lishingizga to'g'ri kelib qoladi. Yuqorida aytilganidek, faylga yozish
kerak deylik. Siz qilmoqchi bo'lgan narsa, buni qilayotgan joyingizni markazlashtirishdir. Muayyan faylga yozadigan bir
nechta funksiya va sinflar yaratmang. Buni amalga oshiradigan bitta servis yarating. Bitta va yagona.
Asosiysi, hech qanday strukturaga ega bo'lmagan ob'ektlar o'rtasida ma'lumot almashinish, har qanday yozilishi mumkin
bo'lgan dinamik ma'lumot turlaridan foydalanish va yon ta'sirlar paydo bo'ladigan joyni markazlashtirmaslik kabi umumiy
tuzoqlardan qochishdir. Agar siz buni amalga oshira olsangiz, boshqa dasturchilarning katta qismidan ko'ra baxtliroq bo'
lasiz.
**Yomon:**
```php
declare(strict_types=1);
// Global oʻzgaruvchiga quyidagi funksiya orqali havola qilingan.
// Agar bizda aynan shu nomdan foydalanadigan boshqa funksiya bo'lganida, endi u massiv bo'lardi va uni buzishi mumkin edi.
$name = 'Ryan McDermott';
function splitIntoFirstAndLastName(): void
{
global $name;
$name = explode(' ', $name);
}
splitIntoFirstAndLastName();
var_dump($name);
// ['Ryan', 'McDermott'];
```
**Yaxshi:**
```php
declare(strict_types=1);
function splitIntoFirstAndLastName(string $name): array
{
return explode(' ', $name);
}
$name = 'Ryan McDermott';
$newName = splitIntoFirstAndLastName($name);
var_dump($name);
// 'Ryan McDermott';
var_dump($newName);
// ['Ryan', 'McDermott'];
```
**[⬆ boshiga qaytish](#mundarija)**
### Global funksiyalarga yozmang
Global funksiyalarga o'zgartirish kiritish ko'p tillarda yomon amaliyotdir, chunki siz boshqa kutubxona bilan to'qnash
kelishingiz mumkin va sizning API foydalanuvchingiz amaliyotga tadbiq etilganda istisnoga duch kelmaguncha muammoli bo'
lib qolaveradi.
Aytaylik, quyidagi misolni ko'rib chiqamiz: agar siz konfiguratsiyani massiv ko'rinishida qabul qilishingizga to'g'ri
kelib qolsa nima bo'ladi? Siz `config()` ga o'xshash global funktsiya yozishingiz mumkin, lekin u xuddi shu vazifani
bajaruvchi boshqa kutubxona bilan muammo yuzaga kelishi mumkin.
**Yomon:**
```php
declare(strict_types=1);
function config(): array
{
return [
'foo' => 'bar',
];
}
```
**Yaxshi:**
```php
declare(strict_types=1);
class Configuration
{
private $configuration = [];
public function __construct(array $configuration)
{
$this->configuration = $configuration;
}
public function get(string $key): ?string
{
// null birlashma operatori
return $this->configuration[$key] ?? null;
}
}
```
Konfiguratsiyalarni chaqirib oling va `Configuration` sinfidan vorislik oling.
```php
declare(strict_types=1);
$configuration = new Configuration([
'foo' => 'bar',
]);
```
Endi esa dasturingizda `Configuration` vorisidan foydalanishingiz kerak.
**[⬆ boshiga qaytish](#mundarija)**
### Singleton pattern'dan foydalanmang
Singleton [anti-pattern](https://en.wikipedia.org/wiki/Singleton_pattern) hisoblanadi. Brian Button shunday deydi:
1. Ular odatda **global instance (global namuna)** sifatida ishlatiladi, nega bu yomon? Chunki siz dasturingiz kodidagi
bog'liqliklarni interfeyslar orqali aniq ko'rsatish o'rniga **bog'liqliklarni yashirasiz**. Biror narsani
tarqatmaslik uchun uni gloabl qilish [code smell](https://en.wikipedia.org/wiki/Code_smell) (koddagi muammoni
ko'rsatishi mumkin bo'lgan umumiy dasturlash xususiyati).
2. Ular o'zlarining yaratilishlari va hayot siklini nazorat qilishlari
tufayli [yagona javobgarlik prinspini](#yagona-javobgarlik-printspi-single-responsibility-principle-srp) buzadi.
3. Ular tabiatan kodni mahkam [bog'lanishiga](https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29) olib
keladi. Bu esa ko'p hollarda **testlash jarayonini qiyinlashtiradi**.
4. Ular dastur ishlashining boshidan oxirigacha ma'lumotlarni olib yuradilar. Bu esa testlashni qiyinlashtiruvchi yana
bir faktor, unit testlashni bajarishda muammoga sabab bo'lishi mumkin. Nega? Chunki har bir unit testlash bir biridan
mustaqil bo'lgani yaxshi.
Bu yerda [muammoning ildizi](http://misko.hevery.com/2008/08/25/root-cause-of-singletons/)
haqida [Misko Hevery](http://misko.hevery.com/about/)ning fikrlarini keltirib o'tilgan.
**Yomon:**
```php
declare(strict_types=1);
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();
```
**Yaxshi:**
```php
declare(strict_types=1);