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 |
||
| 13 | /** |
||
| 14 | * @covers \DVDoug\BoxPacker\BoxList |
||
| 15 | */ |
||
| 16 | class BoxListTest extends TestCase |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * Test that sorting of boxes with different dimensions works as expected i.e. |
||
| 20 | * - Largest (by volume) first. |
||
| 21 | */ |
||
| 22 | public function testSorting() |
||
| 23 | { |
||
| 24 | $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); |
||
| 25 | $box2 = new TestBox('Large', 201, 201, 21, 1, 200, 200, 20, 1000); |
||
| 26 | $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); |
||
| 27 | |||
| 28 | $list = new BoxList(); |
||
| 29 | $list->insert($box1); |
||
| 30 | $list->insert($box2); |
||
| 31 | $list->insert($box3); |
||
| 32 | |||
| 33 | $sorted = iterator_to_array($list, false); |
||
| 34 | self::assertEquals([$box1, $box3, $box2], $sorted); |
||
| 35 | } |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Test that items with a volume greater than 2^31-1 (max signed integer) are sorted correctly. |
||
| 39 | */ |
||
| 40 | public function testIssue30A() |
||
| 41 | { |
||
| 42 | $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); |
||
| 43 | $box2 = new TestBox('Large', 1301, 1301, 1301, 1, 1300, 1300, 1300, 1000); |
||
| 44 | $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); |
||
| 45 | $list = new BoxList(); |
||
| 46 | $list->insert($box1); |
||
| 47 | $list->insert($box2); |
||
| 48 | $list->insert($box3); |
||
| 49 | |||
| 50 | $sorted = iterator_to_array($list, false); |
||
| 51 | self::assertEquals([$box1, $box3, $box2], $sorted); |
||
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Test that items with a volume greater than 2^31-1 (max signed integer) are sorted correctly. |
||
| 56 | */ |
||
| 57 | public function testIssue30B() |
||
| 58 | { |
||
| 59 | $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); |
||
| 60 | $box2 = new TestBox('Large', 1301, 1301, 1301, 1, 1300, 1300, 1300, 1000); |
||
| 61 | $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); |
||
| 62 | $list = new BoxList(); |
||
| 63 | $list->insert($box3); |
||
| 64 | $list->insert($box2); |
||
| 65 | $list->insert($box1); |
||
| 66 | |||
| 67 | $sorted = iterator_to_array($list, false); |
||
| 68 | self::assertEquals([$box1, $box3, $box2], $sorted); |
||
| 69 | |||
| 70 | $list = new BoxList(); |
||
| 71 | $list->insert($box2); |
||
| 72 | $list->insert($box1); |
||
| 73 | $list->insert($box3); |
||
| 74 | |||
| 79 |