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 |
||
24 | class ContactControllerTest extends \PHPUnit_Framework_TestCase { |
||
25 | |||
26 | private $appName; |
||
27 | private $request; |
||
28 | private $contacts; |
||
29 | |||
30 | private $controller; |
||
31 | |||
32 | public function setUp() { |
||
44 | |||
45 | View Code Duplication | public function testSearchLocation() { |
|
|
|||
46 | $expected = [ |
||
47 | [ |
||
48 | 'label' => "33 42nd Street\nRandom Town\nSome State\nUnited States", |
||
49 | 'name' => 'Person 1', |
||
50 | ], |
||
51 | [ |
||
52 | 'label' => "5 Random Ave\n12782 Some big city\nYet another state\nUnited States", |
||
53 | 'name' => 'Person 1', |
||
54 | ], |
||
55 | [ |
||
56 | 'label' => "ABC Street 2\n01337 Village\nGermany", |
||
57 | 'name' => '', |
||
58 | ], |
||
59 | ]; |
||
60 | |||
61 | $apiResponse = [ |
||
62 | [ |
||
63 | 'FN' => 'Person 1', |
||
64 | 'ADR' => [ |
||
65 | '33 42nd Street;Random Town;Some State;;United States', |
||
66 | ';;5 Random Ave;12782 Some big city;Yet another state;United States', |
||
67 | ], |
||
68 | ], |
||
69 | [ |
||
70 | 'FN' => 'Person 2', |
||
71 | ], |
||
72 | [ |
||
73 | 'ADR' => [ |
||
74 | 'ABC Street 2;01337 Village;;Germany', |
||
75 | ], |
||
76 | ], |
||
77 | ]; |
||
78 | |||
79 | $this->contacts->expects($this->once()) |
||
80 | ->method('search') |
||
81 | ->with($this->equalTo('Person'), $this->equalTo(['FN', 'ADR'])) |
||
82 | ->will($this->returnValue($apiResponse)); |
||
83 | |||
84 | $actual = $this->controller->searchLocation('Person'); |
||
85 | |||
86 | $this->assertEquals($expected, $actual->getData()); |
||
87 | |||
88 | } |
||
89 | |||
90 | View Code Duplication | public function testSearchAttendee() { |
|
133 | } |
||
134 |
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.