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 |
||
| 10 | final class Calculator |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * @var NewtonRaphson |
||
| 14 | */ |
||
| 15 | private $newton; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * @param NewtonRaphson $newton |
||
| 19 | */ |
||
| 20 | 8 | public function __construct(NewtonRaphson $newton = null) |
|
| 24 | |||
| 25 | /** |
||
| 26 | * Get the interest when you know all the payments and their dates. Use this function when you have |
||
| 27 | * administration fees at the first payment and/or when payments are irregular. |
||
| 28 | * |
||
| 29 | * @param int $principal |
||
| 30 | * @param string $startDate in format 'YYYY-mm-dd' |
||
| 31 | * @param array $payments array with payment dates and values ['YYYY-mm-dd'=>int] |
||
| 32 | * @param float $guess A guess what the interest may be. Between zero and one. Example 0.045 |
||
| 33 | * |
||
| 34 | * @return float |
||
| 35 | */ |
||
| 36 | 6 | public function withSpecifiedPayments(int $principal, string $startDate, array $payments, float $guess): float |
|
| 60 | |||
| 61 | /** |
||
| 62 | * Get the effective interest when the monthly payments are exactly the same. |
||
| 63 | * |
||
| 64 | * @param int $principal The total loan amount (Principal) |
||
| 65 | * @param int $payment The monthly payment |
||
| 66 | * @param int $numberOfMonths The number of months |
||
| 67 | * @param float $guess A guess of what the interest might be. Interest as a number between zero and one. Example 0.045 |
||
| 68 | * |
||
| 69 | * @return float |
||
| 70 | */ |
||
| 71 | 2 | public function withEqualPayments(int $principal, int $payment, int $numberOfMonths, float $guess): float |
|
| 83 | |||
| 84 | /** |
||
| 85 | * Prepare payment data by separating dates from values and prefix the array with the principal. |
||
| 86 | * |
||
| 87 | * @param int $principal |
||
| 88 | * @param string $startDate |
||
| 89 | * @param array $payments |
||
| 90 | * |
||
| 91 | * @return array |
||
| 92 | */ |
||
| 93 | 6 | private function preparePayments(int $principal, string $startDate, array $payments): array |
|
| 106 | } |
||
| 107 |