简体   繁体   English

对这些嵌套的if / elseif语句有什么更优雅的解决方案?

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

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-generated content, and so I need to display the author of this content in many different locations of the site (comments, posts, etc.). 有很多用户生成内容的机会,因此我需要在网站的许多不同位置(评论,帖子等)显示此内容的作者。 In the user's profile, he is able to (optionally) fill out his "first name", his "last name", and a "display name". 在用户的个人资料中,他能够(可选地)填写他的“名字”,他的“姓氏”和“显示名称”。

To display the author, I wrote a helper method that looks through a provided array of these fields and returns the most appropriate name for the user, in this order of preference: 为了显示作者,我编写了一个帮助器方法,该方法查看这些字段的提供数组,并按此优先顺序返回用户最合适的名称:

  1. If the user filled out display_name , this will be displayed. 如果用户填写了display_name ,则会显示。
  2. If the user filled out first_name and last_name , but no display_name , it will display both names 如果用户填写了first_namelast_name ,但没有显示display_name ,则会显示这两个名称
  3. If the user only filled out first_name , it will display first_name . 如果用户只填写first_name ,它将显示first_name
  4. If the user only filled out last_name , it will display last_name . 如果用户只填写last_name ,它将显示last_name
  5. If all else fails, a user id will be displayed ie user123 如果所有其他方法都失败,将显示用户ID,即user123
  6. If none of the array keys are present, or the parameter is NULL, the name will display as NULL 如果没有数组键,或者参数为NULL,则名称将显示为NULL

The method works great, but it's ugly. 该方法效果很好,但很难看。 There must be a way to beautify this with an alternative to nested if/else statements. 必须有一种方法来替代嵌套的if / else语句来美化它。

public function nameify($names = NULL) {
    $name = '';
    if (!empty($names)) {
        if (!empty($names['display_name'])) {
            $name = $names['display_name'];
        } elseif (!empty($names['first_name'])) {
            $name = $names['first_name'];
            if (!empty($names['last_name'])) {
                $name .= ' ' . $names['last_name'];
            }
        } elseif (!empty($names['last_name'])) {
            $name = $names['last_name'];
        }

        if (empty($name) && !empty($names['id'])) {
            $name = 'user' . $names['id'];
        } else {
            $name = 'NULL';
        }
    } else {
        $name = 'NULL';
    }
    return $name;
}
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 " 编辑:调整以防止返回“NULL”

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;
}

I would propose this: 我建议这个:

public function nameify($names = null) {
    if(empty($names))
        return null;

    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'];
        }
        return $name;
    }

    if(!empty($names['id]))
        return 'user' . $names['id'];

    return null;
}

It is not much, but because $name it is at least NULL: 它并不多,但因为$ name它至少为NULL:

public function nameify($names = NULL) {
    $name = 'NULL';
    if (!empty($names)) {
        if (!empty($names['display_name'])) {
            $name = $names['display_name'];
        } elseif (!empty($names['first_name'])) {
            $name = $names['first_name'];
            if (!empty($names['last_name'])) {
                $name .= ' ' . $names['last_name'];
            }
        } elseif (!empty($names['last_name'])) {
            $name = $names['last_name'];
        }

        if ($name=='NULL' && !empty($names['id'])) {
            $name = 'user' . $names['id'];
        } 
    } 
    return $name;
}

I'd go with: 我会去:

if( empty($names['display_name']) ) {
    $name = $names['first_name'] . ' ' $names['last_name'];
else
    $name = $names['display_name'];

$name = trim($name);
if( empty($name) ) 
    $name = 'user'.$names['id'];
if( empty($name) ) 
    $name = 'NULL';

This would be the 'core logic'... there will need to be other checks like $names != NULL or something.. 这将是'核心逻辑'......需要进行其他检查,比如$names != NULL或者其他什么......

//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++]);
}

Somewhat less readable, but effective): 可读性稍差但有效):

list($idx,$name) = array_shift(array_filter(array(
    $names['display_name'],
    implode(' ',array_filter(array($names['first_name'],$names['last_name']))),
    'user'.$names['id'];
    )));

A State machine works very nicely for involved logic like that. 状态机非常适合这样的逻辑。 It's very simple to implement as well (using a switch statement). 实现起来也非常简单(使用switch语句)。

I'm not sure that my version would be simplier, but here it is: 我不确定我的版本会更简单,但它是:

public function nameify($names = null) {
    $result = array();

    if( !empty($names['display_name']) ) {
        array_push($result,$names['display_name']);
    } else {
        if( !empty($names['first_name']) ) {
            array_push($result, $names['first_name']);
        }
        if( !empty($names['last_name']) ) {
            array_push($result, $names['last_name']);
        }
    }

    if( empty($result) && !empty($names['id']) ) {
        array_push($result, 'user'.$names['id']);
    }

    return (empty($result) ? 'NULL' : implode(' ', $result));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM