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 | class BoxListTest extends \PHPUnit_Framework_TestCase { |
||
| 11 | |||
| 12 | function testCompare() { |
||
| 13 | |||
| 14 | $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); |
||
| 15 | $box2 = new TestBox('Large', 201, 201, 21, 1, 200, 200, 20, 1000); |
||
| 16 | $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); |
||
| 17 | |||
| 18 | $list = new BoxList; |
||
| 19 | $list->insert($box1); |
||
| 20 | $list->insert($box2); |
||
| 21 | $list->insert($box3); |
||
| 22 | |||
| 23 | $sorted = []; |
||
| 24 | while (!$list->isEmpty()) { |
||
| 25 | $sorted[] = $list->extract(); |
||
| 26 | } |
||
| 27 | self::assertEquals(array($box1,$box3,$box2), $sorted); |
||
| 28 | } |
||
| 29 | |||
| 30 | function testIssue14A() { |
||
| 31 | $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); |
||
| 32 | $box2 = new TestBox('Large', 1301, 1301, 1301, 1, 1300, 1300, 1300, 1000); |
||
| 33 | $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); |
||
| 34 | $list = new BoxList; |
||
| 35 | $list->insert($box1); |
||
| 36 | $list->insert($box2); |
||
| 37 | $list->insert($box3); |
||
| 38 | $sorted = []; |
||
| 39 | while (!$list->isEmpty()) { |
||
| 40 | $sorted[] = $list->extract(); |
||
| 41 | } |
||
| 42 | self::assertEquals(array($box1,$box3,$box2), $sorted); |
||
| 43 | } |
||
| 44 | |||
| 45 | function testIssue14B() { |
||
| 46 | $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); |
||
| 47 | $box2 = new TestBox('Large', 1301, 1301, 1301, 1, 1300, 1300, 1300, 1000); |
||
| 48 | $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); |
||
| 49 | $list = new BoxList; |
||
| 50 | $list->insert($box3); |
||
| 51 | $list->insert($box2); |
||
| 52 | $list->insert($box1); |
||
| 53 | $sorted = []; |
||
| 54 | while (!$list->isEmpty()) { |
||
| 55 | $sorted[] = $list->extract(); |
||
| 56 | } |
||
| 57 | self::assertEquals(array($box1,$box3,$box2), $sorted); |
||
| 58 | $list = new BoxList; |
||
| 59 | $list->insert($box2); |
||
| 60 | $list->insert($box1); |
||
| 61 | $list->insert($box3); |
||
| 62 | $sorted = []; |
||
| 63 | while (!$list->isEmpty()) { |
||
| 64 | $sorted[] = $list->extract(); |
||
| 65 | } |
||
| 66 | self::assertEquals(array($box1,$box3,$box2), $sorted); |
||
| 67 | } |
||
| 68 | } |
||
| 69 |