Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 5 | class MaxProductOfThree |
||
| 6 | { |
||
| 7 | public function solution($A) |
||
| 8 | { |
||
| 9 | sort($A); |
||
| 10 | $allPositives = $this->getPositives($A); |
||
| 11 | list($allNegatives, $twoNegatives) = $this->getNegatives($A, $allPositives); |
||
| 12 | |||
| 13 | $maxProduct = null; |
||
| 14 | $values = array_merge($allPositives, $allNegatives, $twoNegatives); |
||
| 15 | $count = count($values); |
||
| 16 | |||
| 17 | for ($i = 0; $i < $count - 2; $i++) { |
||
| 18 | for ($j = $i + 1; $j < $count - 1; $j++) { |
||
| 19 | for ($k = $j + 1; $k < $count; $k++) { |
||
| 20 | $product = $values[$i] * $values[$j] * $values[$k]; |
||
| 21 | if (empty($maxProduct) || $product > $maxProduct) { |
||
| 22 | $maxProduct = $product; |
||
| 23 | } |
||
| 24 | } |
||
| 25 | } |
||
| 26 | } |
||
| 27 | |||
| 28 | return $maxProduct; |
||
| 29 | } |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @param $A |
||
| 33 | * |
||
| 34 | * @return array |
||
| 35 | * |
||
| 36 | * @internal param $arrayCount |
||
| 37 | * @internal param $allPositives |
||
| 38 | */ |
||
| 39 | private function getPositives($A) |
||
| 51 | |||
| 52 | /** |
||
| 53 | * @param $A |
||
| 54 | * @param $allPositives |
||
| 55 | * |
||
| 56 | * @return array |
||
| 57 | * |
||
| 58 | * @internal param $arrayCount |
||
| 59 | * @internal param $allNegatives |
||
| 60 | * @internal param $twoNegatives |
||
| 61 | */ |
||
| 62 | private function getNegatives($A, $allPositives) |
||
| 85 | } |
||
| 86 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.