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 MoneyController 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 MoneyController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
11 | class MoneyController extends adminController { |
||
12 | |||
13 | public function manualClosePayAction($payId) { |
||
14 | $pay = \Money\Pay::get((int) $payId); |
||
15 | $result = new Server\Result(); |
||
16 | if ($pay && $pay->pay_status_id == 1) { |
||
17 | $pay->pay_status_id = 2; |
||
18 | $pay->save(); |
||
19 | if ($pay->callback_module && $pay->callback_method) { |
||
20 | \App::$primary->{$pay->callback_module}->{$pay->callback_method}(['status' => 'success', 'payId' => $pay->id, 'pay' => $pay]); |
||
21 | } |
||
22 | $result->successMsg = 'Счет был проведен'; |
||
23 | $result->send(); |
||
24 | } |
||
25 | $result->success = false; |
||
26 | $result->content = 'Такой счет не найден'; |
||
27 | $result->send(); |
||
28 | } |
||
29 | |||
30 | public function cancelTransferAction($transferId) { |
||
31 | $transfer = Money\Transfer::get($transferId); |
||
32 | $result = new Server\Result(); |
||
33 | |||
34 | $result->success = $transfer->cancel(); |
||
35 | |||
36 | $result->successMsg = 'Перевод был отменен'; |
||
37 | $result->content = 'Не удалось отменить перевод'; |
||
38 | $result->send(); |
||
39 | } |
||
40 | |||
41 | public function completeTransferAction($transferId) { |
||
51 | } |
||
52 | |||
53 | } |
||
54 |