What is a more elegant solution to these nested if/elseif statements?

后端 未结 9 1834
野趣味
野趣味 2021-01-12 17:09

I\'m building a website that contains users with user profiles. Many of the fields in the profile are optional.

There is an opportunity for a lot of user-generate

相关标签:
9条回答
  • 2021-01-12 18:06

    Using ternary conditions we can shorten and beautify the code:

    public function nameify($names = NULL) {
        $name = 'NULL';
    
        if (!empty($names)) {
    
            $name = ($names['display_name']) ? $names['display_name'] : trim($names['first_name']." ".$names['last_name']);
    
            if(!$name) $name = ($names['id'] > 0) ? 'user'.$names['id'] : 'NULL';
        }
    
        return $name;
    }
    
    0 讨论(0)
  • 2021-01-12 18:09
    //pointers to functions
    $arrayOfSulutions{"display_name_strategy", "full_name_strategy" ..., "null_strategy" } 
    function display_name_strategy{
         return $names['display_name'];
    }
    $i = 0;
    while($res == null){
         $res = call($arrayOfSulutions[$i++]);
    }
    
    0 讨论(0)
  • 2021-01-12 18:12
    public function nameify($names = NULL) {
        if ($names) {
            if (!empty($names['display_name'])) {
                return $names['display_name'];
            }
            if (!empty($names['first_name'])) {
                $name = $names['first_name'];
            } 
            if (!empty($names['last_name'])) {
                $name .= ' ' . $names['last_name'];
            }
            if (empty($name) && !empty($names['id'])) {
                $name = 'user' . $names['id'];
            }
        }
        return $name ? ltrim($name) : 'NULL';
    }
    

    Set the default first, and return that if nothing else matches. Then since we always want to return the display name if we have it do just that.

    EDIT: Tweak to prevent returning "NULL "

    0 讨论(0)
提交回复
热议问题