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 |
||
| 11 | abstract class ObjectAction implements Action { |
||
| 12 | |||
| 13 | /** @var PropertyReader */ |
||
| 14 | private $reader; |
||
| 15 | |||
| 16 | /** @var \ReflectionClass */ |
||
| 17 | protected $class; |
||
| 18 | |||
| 19 | /** @var CommentParser */ |
||
| 20 | private $parser; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @param string $class |
||
| 24 | * @param TypeFactory $types |
||
| 25 | * @param CommentParser $parser |
||
| 26 | */ |
||
| 27 | public function __construct($class, TypeFactory $types, CommentParser $parser) { |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Called by execute() with the instantiated object |
||
| 35 | * |
||
| 36 | * @param object $object |
||
| 37 | * @return mixed |
||
| 38 | */ |
||
| 39 | abstract protected function executeWith($object); |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @return string |
||
| 43 | */ |
||
| 44 | public function caption() { |
||
| 47 | |||
| 48 | /** |
||
| 49 | * @return string|null |
||
| 50 | */ |
||
| 51 | public function description() { |
||
| 61 | |||
| 62 | /** |
||
| 63 | * Fills out partially available parameters |
||
| 64 | * |
||
| 65 | * @param array $parameters Available values indexed by name |
||
| 66 | * @return array Filled values indexed by name |
||
| 67 | */ |
||
| 68 | public function fill(array $parameters) { |
||
| 76 | |||
| 77 | /** |
||
| 78 | * @return Parameter[] |
||
| 79 | * @throws \Exception |
||
| 80 | */ |
||
| 81 | public function parameters() { |
||
| 91 | |||
| 92 | /** |
||
| 93 | * @return boolean True if the action modifies the state of the application |
||
| 94 | */ |
||
| 95 | public function isModifying() { |
||
| 98 | |||
| 99 | /** |
||
| 100 | * @param mixed[] $parameters Values indexed by name |
||
| 101 | * @return mixed the result of the execution |
||
| 102 | * @throws \Exception if Action cannot be executed |
||
| 103 | */ |
||
| 104 | public function execute(array $parameters) { |
||
| 107 | |||
| 108 | protected function createInstance(array $parameters) { |
||
| 121 | } |
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.