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 |
||
25 | class StreetAdvisorAPI { |
||
26 | /** |
||
27 | * API Key. |
||
28 | * |
||
29 | * @var string |
||
30 | */ |
||
31 | static private $api_key; |
||
32 | /** |
||
33 | * URL to the API. |
||
34 | * |
||
35 | * @var string |
||
36 | */ |
||
37 | private $base_uri = 'https://web-api-legacy.streetadvisor.com'; |
||
38 | /** |
||
39 | * __construct function. |
||
40 | * |
||
41 | * @access public |
||
42 | * @param mixed $api_key API Key. |
||
43 | * @return void |
||
44 | */ |
||
45 | public function __construct( $api_key ) { |
||
52 | /** |
||
53 | * Fetch the request from the API. |
||
54 | * |
||
55 | * @access private |
||
56 | * @param mixed $request Request URL. |
||
57 | * @return $body Body. |
||
58 | */ |
||
59 | View Code Duplication | private function fetch( $request ) { |
|
68 | /** |
||
69 | * Get Location Data. |
||
70 | * |
||
71 | * @access public |
||
72 | * @param mixed $latitude Latitude. |
||
73 | * @param mixed $longitude Longitude. |
||
74 | * @param mixed $level Level. |
||
75 | * @return void |
||
76 | */ |
||
77 | public function get_location_data( $latitude, $longitude, $level ) { |
||
81 | /** |
||
82 | * Get Location Reviews. |
||
83 | * |
||
84 | * @access public |
||
85 | * @param mixed $latitude Latitude. |
||
86 | * @param mixed $longitude Longitude. |
||
87 | * @param mixed $level Level. |
||
88 | * @param int $review_count (default: 5) Total # of Reviews to display. |
||
89 | * @return void |
||
90 | */ |
||
91 | public function get_location_reviews( $latitude, $longitude, $level, $review_count = '5' ) { |
||
95 | } |
||
96 | } |
||
97 |
The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.
The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.
To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.