Conditions | 10 |
Paths | 14 |
Total Lines | 33 |
Code Lines | 25 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
11 | public static function calculate(string $s): int |
||
12 | { |
||
13 | if (empty($s)) { |
||
14 | return 0; |
||
15 | } |
||
16 | $s = str_replace(' ', '', $s); |
||
17 | $n = strlen($s); |
||
18 | [$stack, $num, $operator] = [[], 0, '+']; |
||
19 | for ($i = 0; $i < $n; $i++) { |
||
20 | $char = $s[$i]; |
||
21 | if (is_numeric($char)) { |
||
22 | $num = $char; |
||
23 | } |
||
24 | if ($i === $n - 1 || in_array($char, self::$operators)) { |
||
25 | switch ($operator) { |
||
26 | case '+': |
||
27 | array_push($stack, $num); |
||
28 | break; |
||
29 | case '-': |
||
30 | array_push($stack, -$num); |
||
31 | break; |
||
32 | case '*': |
||
33 | array_push($stack, (int)(array_pop($stack) * $num)); |
||
34 | break; |
||
35 | case '/': |
||
36 | array_push($stack, (int)(array_pop($stack) / $num)); |
||
37 | break; |
||
38 | } |
||
39 | [$num, $operator] = [0, $char]; |
||
40 | } |
||
41 | } |
||
42 | |||
43 | return array_sum($stack); |
||
|
|||
44 | } |
||
78 |