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 |
||
8 | class Calculator |
||
9 | { |
||
10 | /** |
||
11 | * @var NewtonRaphson |
||
12 | */ |
||
13 | private $newton; |
||
14 | |||
15 | /** |
||
16 | * @param NewtonRaphson $newton |
||
17 | */ |
||
18 | public function __construct(NewtonRaphson $newton = null) |
||
22 | |||
23 | /** |
||
24 | * Get the interest when you know all the payments and their dates. Use this function when you have |
||
25 | * administration fees at the first payment and/or when payments are irregular. |
||
26 | * |
||
27 | * @param int $principal |
||
28 | * @param string $startDate in format 'YYYY-mm-dd' |
||
29 | * @param array $payments array with payment dates and values ['YYYY-mm-dd'=>int] |
||
30 | * @param float $guess A guess what the interest may be. Between zero and one. Example 0.045 |
||
31 | * |
||
32 | * @return float |
||
33 | */ |
||
34 | public function withSpecifiedPayments(int $principal, string $startDate, array $payments, float $guess): float |
||
65 | |||
66 | /** |
||
67 | * Get the effective interest when the monthly payments are exactly the same. |
||
68 | * |
||
69 | * @param int $a The total loan amount (Principal) |
||
70 | * @param int $p The monthly payment |
||
71 | * @param int $n The number of months |
||
72 | * @param float $i A guess of what the interest might be. Interest as a number between zero and one. Example 0.045 |
||
73 | * |
||
74 | * @return float |
||
75 | */ |
||
76 | public function withEqualPayments(int $a, int $p, int $n, float $i): float |
||
88 | } |
||
89 |
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.