1
\$\begingroup\$

This code is from my Kohana project. How can I make it more beautiful? Should I use try-catch instead? How could I avoid writing exit() twice?

public function action_index()
{
    $id = $this->request->query('id');
    if (!empty($id)) {
        $ticket = ORM::factory('ticket')
            ->where('id', '=', $id)
            ->find();
        if (!empty($ticket)) {
            $event = ORM::factory('event')
                ->where('id', '=', $ticket->event_id)
                ->find();
            if (!empty($event)) {
                $this->template->ticket = $ticket->id;
                $this->template->name = $ticket->name;
                $this->template->event = $event->title;
            } else {
                exit();
            }
        } else {
            exit();
        }
    }
}
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

You can avoid writing exit() twice by adding a return statement at the deepest level, after passing all the checks. This should be equivalent to your code:

public function action_index()
{
    $id = $this->request->query('id');
    if (!empty($id)) {
        $ticket = ORM::factory('ticket')
            ->where('id', '=', $id)
            ->find();
        if (!empty($ticket)) {
            $event = ORM::factory('event')
                ->where('id', '=', $ticket->event_id)
                ->find();
            if (!empty($event)) {
                $this->template->ticket = $ticket->id;
                $this->template->name = $ticket->name;
                $this->template->event = $event->title;
                return;
            }
        }
        exit();
    }
}

That said, I find it a bit strange to exit() in the middle of a function. It's an abrupt behavior in a program in general, this kind of control is usually done at higher levels, in order to do any necessary cleanup, such as releasing resources, closing connections.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.