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 |
||
| 15 | class Requests_Utility_CaseInsensitiveDictionary implements ArrayAccess, IteratorAggregate { |
||
| 16 | /** |
||
| 17 | * Actual item data |
||
| 18 | * |
||
| 19 | * @var array |
||
| 20 | */ |
||
| 21 | protected $data = array(); |
||
| 22 | |||
| 23 | /** |
||
| 24 | * Creates a case insensitive dictionary. |
||
| 25 | * |
||
| 26 | * @param array $data Dictionary/map to convert to case-insensitive |
||
| 27 | */ |
||
| 28 | public function __construct(array $data = array()) { |
||
| 33 | |||
| 34 | /** |
||
| 35 | * Check if the given item exists |
||
| 36 | * |
||
| 37 | * @param string $key Item key |
||
| 38 | * @return boolean Does the item exist? |
||
| 39 | */ |
||
| 40 | public function offsetExists($key) { |
||
| 44 | |||
| 45 | /** |
||
| 46 | * Get the value for the item |
||
| 47 | * |
||
| 48 | * @param string $key Item key |
||
| 49 | * @return string|null Item value (null if offsetExists is false) |
||
| 50 | */ |
||
| 51 | View Code Duplication | public function offsetGet($key) { |
|
| 59 | |||
| 60 | /** |
||
| 61 | * Set the given item |
||
| 62 | * |
||
| 63 | * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`) |
||
| 64 | * |
||
| 65 | * @param string $key Item name |
||
| 66 | * @param string $value Item value |
||
| 67 | */ |
||
| 68 | public function offsetSet($key, $value) { |
||
| 76 | |||
| 77 | /** |
||
| 78 | * Unset the given header |
||
| 79 | * |
||
| 80 | * @param string $key |
||
| 81 | */ |
||
| 82 | public function offsetUnset($key) { |
||
| 85 | |||
| 86 | /** |
||
| 87 | * Get an iterator for the data |
||
| 88 | * |
||
| 89 | * @return ArrayIterator |
||
| 90 | */ |
||
| 91 | public function getIterator() { |
||
| 94 | |||
| 95 | /** |
||
| 96 | * Get the headers as an array |
||
| 97 | * |
||
| 98 | * @return array Header data |
||
| 99 | */ |
||
| 100 | public function getAll() { |
||
| 103 | } |
||
| 104 |
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.