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 |
||
| 28 | class RongcloudGateway extends Gateway |
||
| 29 | { |
||
| 30 | use HasHttpRequest; |
||
| 31 | |||
| 32 | const ENDPOINT_TEMPLATE = 'http://api.sms.ronghub.com/%s.%s'; |
||
| 33 | |||
| 34 | const ENDPOINT_ACTION = 'sendCode'; |
||
| 35 | |||
| 36 | const ENDPOINT_FORMAT = 'json'; |
||
| 37 | |||
| 38 | const ENDPOINT_REGION = '86'; // 中国区,目前只支持此国别 |
||
| 39 | |||
| 40 | const SUCCESS_CODE = 200; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @param \Overtrue\EasySms\Contracts\PhoneNumberInterface $to |
||
| 44 | * @param \Overtrue\EasySms\Contracts\MessageInterface $message |
||
| 45 | * @param \Overtrue\EasySms\Support\Config $config |
||
| 46 | * |
||
| 47 | * @return array |
||
| 48 | * |
||
| 49 | * @throws \Overtrue\EasySms\Exceptions\GatewayErrorException ; |
||
| 50 | */ |
||
| 51 | public function send(PhoneNumberInterface $to, MessageInterface $message, Config $config) |
||
| 109 | |||
| 110 | /** |
||
| 111 | * Generate Sign. |
||
| 112 | * |
||
| 113 | * @param array $params |
||
| 114 | * @param \Overtrue\EasySms\Support\Config $config |
||
| 115 | * |
||
| 116 | * @return string |
||
| 117 | */ |
||
| 118 | protected function generateSign($params, Config $config) |
||
| 122 | |||
| 123 | /** |
||
| 124 | * Build endpoint url. |
||
| 125 | * |
||
| 126 | * @param string $action |
||
| 127 | * |
||
| 128 | * @return string |
||
| 129 | */ |
||
| 130 | protected function buildEndpoint($action) |
||
| 134 | } |
||
| 135 |
PHP has two types of connecting operators (logical operators, and boolean operators):
and&&or||The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like
&&, or||.Let’s take a look at a few examples:
Logical Operators are used for Control-Flow
One case where you explicitly want to use logical operators is for control-flow such as this:
Since
dieintroduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined withthrowat this point:These limitations lead to logical operators rarely being of use in current PHP code.