Conditions | 10 |
Paths | 9 |
Total Lines | 42 |
Code Lines | 22 |
Lines | 7 |
Ratio | 16.67 % |
Changes | 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 |
||
62 | public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr) |
||
63 | { |
||
64 | if ($this->bowOutEarly() === true) { |
||
65 | return; |
||
66 | } |
||
67 | |||
68 | $tokens = $phpcsFile->getTokens(); |
||
69 | |||
70 | if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY |
||
71 | && $this->isShortList($phpcsFile, $stackPtr) === false |
||
72 | ) { |
||
73 | // Short array, not short list. |
||
74 | return; |
||
75 | } |
||
76 | |||
77 | if ($tokens[$stackPtr]['code'] === T_LIST) { |
||
78 | $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true); |
||
79 | View Code Duplication | if ($nextNonEmpty === false |
|
80 | || $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS |
||
81 | || isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false |
||
82 | ) { |
||
83 | // Parse error or live coding. |
||
84 | return; |
||
85 | } |
||
86 | |||
87 | $opener = $nextNonEmpty; |
||
88 | $closer = $tokens[$nextNonEmpty]['parenthesis_closer']; |
||
89 | } else { |
||
90 | // Short list syntax. |
||
91 | $opener = $stackPtr; |
||
92 | |||
93 | if (isset($tokens[$stackPtr]['bracket_closer'])) { |
||
94 | $closer = $tokens[$stackPtr]['bracket_closer']; |
||
95 | } |
||
96 | } |
||
97 | |||
98 | if (isset($opener, $closer) === false) { |
||
99 | return; |
||
100 | } |
||
101 | |||
102 | $this->examineList($phpcsFile, $opener, $closer); |
||
|
|||
103 | } |
||
104 | |||
176 |
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: