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:
Complex classes like UndoUpvoteAnswer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use UndoUpvoteAnswer, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
34 | public function __construct(HttpClient $client, Serializer $serializer, Authentication $authentication) |
||
35 | { |
||
36 | $this->client = $client; |
||
37 | $this->serializer = $serializer; |
||
38 | $this->authentication = $authentication; |
||
39 | } |
||
40 | |||
41 | public function __invoke(string $id, array $parameters = AnswerApi::QUERY_PARAMS) |
||
50 | |||
51 | private function url(string $id) : string |
||
55 | |||
56 | private function mergeAuthenticationIntoParameters(array $parameters) : array |
||
60 | } |
||
61 |
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.