For this use case, creating one record depends on successful creating another record in another database table as following.
$user = $this->createUser();
if ($user) {
// I skip how $user is being used here.
$order = $this->createOrder();
if ($order) {
// I skip how $order is being used here.
$invoice = $this->createInvoice();
if ($invoice) {
// I skip how $invoice is being used here.
$payment = $this->createPayment();
if ($payment) {
// I skip how $payment is being used here.
$shipping = $this->createShipping();
if ($shipping) {
$this->notifyCustomer();
}
}
}
}
}
I do understand that writing many nested if-statements is not a good practice. Is the following code snippet a better alternative?
$user = $this->createUser();
$order = null;
if ($user) {
// I skip how $user is being used here.
$order = $this->createOrder();
}
$invoice = null;
if ($order) {
// I skip how $order is being used here.
$invoice = $this->createInvoice();
}
$payment = null;
if ($invoice) {
// I skip how $invoice is being used here.
$payment = $this->createPayment();
}
$shipping = null;
if ($payment) {
// I skip how $payment is being used here.
$shipping = $this->createShipping();
}
if ($shipping) {
$this->notifyCustomer();
}
Why I doubt about this solution is because several variables are declared for just to escape the nested if-statements.
Aucun commentaire:
Enregistrer un commentaire