Recently, to avoid overly nested If I use the principle of early return. However, there are situations when this principle can "clog" the code. For example, today you need to return json with the results, so you can do this:
public function canSendSms( ) { $shopId = $this->request->post['shop_id']; $dateEnd = $this->request->post['dateEnd']; $orderId = $this->request->post['order_id']; if ( ! $shopId || !$dateEnd || !$orderId ) { $result["error"][] = "Неверные данные"; header("Content-type: application/json"); return json_encode($result, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE); } // Собираем оставшиеся данные $this->load->model('sale/order'); $order_info = $this->model_sale_order->getOrder($orderId); if ( !$order_info ) { $result["error"][] = "Не получилось найти заказ под номером " . $orderId; header("Content-type: application/json"); return json_encode($result, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE); } // финальный код $result["success"][] = "Сообщение можно отправить"; header("Content-type: application/json"); return json_encode($result, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE); } Apparently from an example - here 2 lines of an output here are repeated 3 times
header("Content-type: application/json"); return json_encode($result, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE); If the method is small and no changes are planned, then there are no problems. But what if there are 10 such checks, and the output format changes from json to some other one? Well, yes, you have to stupidly change the output in these 10 checks.
In this regard, I began to use recursion, as a result, the final return is now always in such cases at the beginning of the method. It looks that way.
public function canSendSms( $result = NULL ) { if ( $result ) { header("Content-type: application/json"); echo json_encode($result, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE); return; } $shopId = $this->request->post['shop_id']; $dateEnd = $this->request->post['dateEnd']; $orderId = $this->request->post['order_id']; if ( ! $shopId || !$dateEnd || !$orderId ) { $result["error"][] = "Неверные данные"; return $this->canSendSms( $result ); } // Собираем оставшиеся данные $this->load->model('sale/order'); $order_info = $this->model_sale_order->getOrder($orderId); if ( !$order_info ) { $result["error"][] = "Не получилось найти заказ под номером " . $orderId; return $this->canSendSms( $result ); } // какой-то код $result["success"][] = "Сообщение можно отправить"; return $this->canSendSms( $result ); } The question is, how correct is it, how understandable, and is there anything similar in your practice?