You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<img src="/docs/required_type_level.jpg" style="width: 25em" alt="AI abilities sea level rising... as way to rise type coverage for class elements">
7
-
</div>
5
+
Cognitive complexity tells us, how difficult code is to understand by a reader.
8
6
9
-
<br>
10
-
11
-
PHPStan uses type declarations to determine the type of variables, properties and other expression. Sometimes it's hard to see what PHPStan errors are the important ones among thousands of others.
12
-
13
-
Instead of fixing all PHPStan errors at once, we can start with minimal require type coverage.
14
-
15
-
<br>
16
-
17
-
What is the type coverage you ask? We have 3 type possible declarations in total here:
7
+
**How is cognitive compleixty measured?**
18
8
19
9
```php
20
-
final class ConferenceFactory
21
-
{
22
-
private $talkFactory;
23
-
24
-
public function createConference(array $data)
25
-
{
26
-
$talks = $this->talkFactory->create($data);
27
-
28
-
return new Conference($talks);
10
+
function sumOfPrimes($max) {
11
+
$total = 0;
12
+
for ($i = 1; $i < $max; ++$i) { // +1
13
+
for ($j = 2; $j < $i; ++$j) { // +2
14
+
if ($i % $j === 0) { // +3
15
+
continue 2; // +1
16
+
}
17
+
}
18
+
19
+
$total += $i;
29
20
}
21
+
22
+
return $total;
30
23
}
31
24
```
32
25
33
-
The param type is defined, but property and return types are missing.
34
-
35
-
* 1 out of 3 = 33 % coverage
36
-
37
-
How do we get to the 100 %?
38
-
39
-
```diff
40
-
final class ConferenceFactory
41
-
{
42
-
- private $talkFactory;
43
-
+ private TalkFactory $talkFactory;
44
-
45
-
- public function createConference(array $data)
46
-
+ public function createConference(array $data): Conference
47
-
{
48
-
$talks = $this->talkFactory->create($data);
49
-
50
-
return new Conference($talks);
51
-
}
52
-
}
53
-
```
26
+
This function uses nesting, conditions and continue back and forth. It's hard to read and has complexity of 7.
54
27
55
-
This technique is very simple and useful to start with even on legacy project. You also know, how high coverage your project has right now.
28
+
How to keep it down and what else is included in measurements? Check [Is Your Code Readable By Humans?](https://tomasvotruba.com/blog/2018/05/21/is-your-code-readable-by-humans-cognitive-complexity-tells-you/) post to learn it.
0 commit comments