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

时间:2018-10-02 21:33:19

标签: javascript sonarlint

对于下面的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 个答案:

答案 0 :(得分:0)

也许是这样的:

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;
}
寻找你感兴趣的贴纸↓↓↓
豫ICP备18024241号-1