Javascript SonarQube 重构此功能以降低其认知复杂性
Javascript SonarQube refactor this function to reduce its Cognitive Complexity
对于下面的 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 = "";
}
}
可能是这样的:
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;
}
对于下面的 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 = "";
}
}
可能是这样的:
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;
}