当前位置: 首页 > 知识库问答 >
问题:

Javascript SonarQube重构了该函数以降低其认知复杂性

须曜文
2023-03-14

对于下面的JavaScript函数,我试图找出如何降低认知复杂性。

function Person(data) {
    var self = this;
    if (data) {
        self.id = data.Id === null? "" : data.Id;
        self.name = data.Name === null? "" : data.Name;
        self.phone= data.Phone === null? "" : data.Phone;
        self.address = data.Address=== null ? "" : data.Address;
    } else {
        self.id = "";
        self.name = "";
        self.phone = "";
        self.address = "";
    }
}

共有1个答案

夹谷茂
2023-03-14

也许是这样的:

function Person(data) {
    var self = this;

    self.id = "";
    self.name = "";
    self.phone = "";
    self.address = "";

    if (data) {
        self.id = getValueOrDefault(data.Id);
        self.name = getValueOrDefault(data.Name);
        self.phone = getValueOrDefault(data.Phone);
        self.address = getValueOrDefault(data.Address);
    }
}

function getValueOrDefault(value) {
    return value === null ? "" : value;
}
 类似资料: