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 |
||
| 32 | class UserGroupMembership implements ICheck { |
||
| 33 | |||
| 34 | /** @var string */ |
||
| 35 | protected $cachedUser; |
||
| 36 | |||
| 37 | /** @var string[] */ |
||
| 38 | protected $cachedGroupMemberships; |
||
| 39 | |||
| 40 | /** @var IUserSession */ |
||
| 41 | protected $userSession; |
||
| 42 | |||
| 43 | /** @var IGroupManager */ |
||
| 44 | protected $groupManager; |
||
| 45 | |||
| 46 | /** @var IL10N */ |
||
| 47 | protected $l; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @param IUserSession $userSession |
||
| 51 | * @param IGroupManager $groupManager |
||
| 52 | * @param IL10N $l |
||
| 53 | */ |
||
| 54 | public function __construct(IUserSession $userSession, IGroupManager $groupManager, IL10N $l) { |
||
| 59 | |||
| 60 | /** |
||
| 61 | * @param IStorage $storage |
||
| 62 | * @param string $path |
||
| 63 | */ |
||
| 64 | public function setFileInfo(IStorage $storage, $path) { |
||
| 67 | |||
| 68 | /** |
||
| 69 | * @param string $operator |
||
| 70 | * @param string $value |
||
| 71 | * @return bool |
||
| 72 | */ |
||
| 73 | public function executeCheck($operator, $value) { |
||
| 83 | |||
| 84 | |||
| 85 | /** |
||
| 86 | * @param string $operator |
||
| 87 | * @param string $value |
||
| 88 | * @throws \UnexpectedValueException |
||
| 89 | */ |
||
| 90 | public function validateCheck($operator, $value) { |
||
| 91 | View Code Duplication | if (!in_array($operator, ['is', '!is'])) { |
|
|
|
|||
| 92 | throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1); |
||
| 93 | } |
||
| 94 | |||
| 95 | if (!$this->groupManager->groupExists($value)) { |
||
| 96 | throw new \UnexpectedValueException($this->l->t('The given group does not exist'), 2); |
||
| 97 | } |
||
| 98 | } |
||
| 99 | |||
| 100 | /** |
||
| 101 | * @param IUser $user |
||
| 102 | * @return string[] |
||
| 103 | */ |
||
| 104 | protected function getUserGroups(IUser $user) { |
||
| 114 | } |
||
| 115 |
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.