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 |
||
| 23 | class HttpHelper |
||
| 24 | { |
||
| 25 | protected $options = []; |
||
| 26 | protected $requestUri = ''; |
||
| 27 | protected $requestMethod = 'GET'; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * HttpHelper for Guzzle operations. |
||
| 31 | * |
||
| 32 | * @param httpClient $httpClient Sf Request information service |
||
| 33 | */ |
||
| 34 | public function __construct( |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @param string $uri Remote server Base url |
||
| 42 | * @return void |
||
| 43 | */ |
||
| 44 | public function setBaseUri($uri) |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @param string $uri Remote server Base url |
||
| 51 | * @return void |
||
| 52 | */ |
||
| 53 | public function setRequestUri($uri) |
||
| 57 | |||
| 58 | /** |
||
| 59 | * @param string $method GET | POST | ... |
||
| 60 | * @return void |
||
| 61 | */ |
||
| 62 | public function setMethod($method) |
||
| 66 | |||
| 67 | /** |
||
| 68 | * Client request header |
||
| 69 | * |
||
| 70 | * @param string $name key field |
||
| 71 | * @param string $value assignation |
||
| 72 | * @return void |
||
| 73 | */ |
||
| 74 | View Code Duplication | public function addHeader($name, $value) |
|
| 81 | |||
| 82 | /** |
||
| 83 | * Client request query params |
||
| 84 | * |
||
| 85 | * @param string $name key field |
||
| 86 | * @param string $value assignation |
||
| 87 | * @return void |
||
| 88 | */ |
||
| 89 | View Code Duplication | public function addQueryParams($name, $value) |
|
| 96 | |||
| 97 | /** |
||
| 98 | * Run request against server |
||
| 99 | * |
||
| 100 | * @return Response |
||
| 101 | */ |
||
| 102 | public function execute() |
||
| 132 | } |
||
| 133 |
PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.
Let’s take a look at an example:
If we look at the
getEmail()method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:On the hand, if we look at the
setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call: