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 |
||
21 | class QueryReducer { |
||
22 | |||
23 | /** |
||
24 | * @var \Youshido\GraphQL\Execution\Request |
||
25 | */ |
||
26 | protected $request; |
||
27 | |||
28 | /** |
||
29 | * @var \Youshido\GraphQL\Schema\AbstractSchema |
||
30 | */ |
||
31 | protected $schema; |
||
32 | |||
33 | /** |
||
34 | * @var \Youshido\GraphQL\Type\TypeInterface[] |
||
35 | */ |
||
36 | protected $types; |
||
37 | |||
38 | /** |
||
39 | * QueryReducer constructor. |
||
40 | * |
||
41 | * @param \Youshido\GraphQL\Schema\AbstractSchema $schema |
||
42 | * @param \Youshido\GraphQL\Execution\Request $request |
||
43 | */ |
||
44 | public function __construct(AbstractSchema $schema, Request $request) { |
||
49 | |||
50 | /** |
||
51 | * @param \Drupal\graphql\GraphQL\Execution\QueryVisitor\QueryVisitorInterface $visitor |
||
52 | * |
||
53 | * @return mixed|\Youshido\GraphQL\Parser\Ast\Query |
||
54 | */ |
||
55 | public function reduceQuery(QueryVisitorInterface $visitor) { |
||
63 | |||
64 | /** |
||
65 | * @param \Youshido\GraphQL\Parser\Ast\Query $query |
||
66 | * @param $carry |
||
67 | * @param $current |
||
68 | * @param \Drupal\graphql\GraphQL\Execution\QueryVisitor\QueryVisitorInterface $visitor |
||
69 | * |
||
70 | * @return mixed|void |
||
71 | */ |
||
72 | protected function reduceOperation(Query $query, $carry, $current, QueryVisitorInterface $visitor) { |
||
96 | |||
97 | /** |
||
98 | * @param $node |
||
99 | * @param \Youshido\GraphQL\Field\FieldInterface $current |
||
100 | * @param \Drupal\graphql\GraphQL\Execution\QueryVisitor\QueryVisitorInterface $visitor |
||
101 | * |
||
102 | * @return \Generator |
||
103 | */ |
||
104 | protected function walkQuery(AbstractAst $node, FieldInterface $current, QueryVisitorInterface $visitor) { |
||
147 | |||
148 | /** |
||
149 | * @param \Youshido\GraphQL\Parser\Ast\AbstractAst $node |
||
150 | * @param \Youshido\GraphQL\Field\FieldInterface $current |
||
151 | * |
||
152 | * @return null|\Youshido\GraphQL\Type\AbstractType|\Youshido\GraphQL\Type\TypeInterface |
||
153 | */ |
||
154 | protected function getType(AbstractAst $node, FieldInterface $current) { |
||
165 | |||
166 | } |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: