dimanche 21 janvier 2018

Else statements and coding practice

Take the following example:

public function exists() {
    $profile_picture = $this->details->profile_image;
    $image = $this->images->get_images($profile_picture, true);
    if (is_string($image)) {
        return false;
    }
    $this->profile_picture->pp_main = $image[0]['main'];
    $this->profile_picture->pp_thumb = $image[0]['thumb'];
    return true;
}

and else statement can be used like so:

public function exists() {
    $profile_picture = $this->details->profile_image;
    $image = $this->images->get_images($profile_picture, true);
    if (is_string($image)) {
        return false;
    } else {
        $this->profile_picture->pp_main = $image[0]['main'];
        $this->profile_picture->pp_thumb = $image[0]['thumb'];
        return true;
    }
}

its presence does not fundamentally change the code at all.

What is considered best practice (to else or not to else)? To me the first method seems cleaner.

public function view_log($log_name = null) {
    if (!$this->input->is_ajax_request()) {
        exit('No direct script access allowed');
    }
    if (is_null($log_name)) {
        encode_response('error', $this->lang->line('messages_missing_params'));
    }
    $count = 1;
    $out = '';
    $log = $this->log->print_log($log_name);
    if ($log === false) {
        encode_response('error', 'Invalid/non-existent log selected.'); // exits
    }
    foreach ($log as $error) {
        if (empty($error)) {
            continue;
        }
        $out .= "<strong>Error {$count}</strong><br><code>{$error}</code><br><br>";
        $count++;
    }
    encode_response('success', $out); // exits
}

I often find myself doing this kind of logic a lot in controllers where I have functions that render errors .etc. because I feel an else statement is both useless in this circumstance, and would add extra indentations.

Aucun commentaire:

Enregistrer un commentaire