dev
dev

Reputation: 918

Javascript SonarQube refactor this function to reduce its Cognitive Complexity

For below JavaScript function i am trying to figure out how to reduce the Cognitive Complexity.

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

Upvotes: 5

Views: 9687

Answers (2)

Tulio Pinto Neto
Tulio Pinto Neto

Reputation: 1

You can use optional chaining along with short-circuit operator.

With the optional chaining, you avoid calling to the parameters (Id, Name, Phone, Address) and return undefined directly. Then with the short-circuit operator you will pass the default value, in the case the left side returning a undefined.

function Person(data) {
  this.id = data?.Id || "";
  this.name = data?.Name || "";
  this.phone = data?.Phone || "";
  this.address = data?.Address || "";
}

More on why those are good options for legibility (which is related to Cognitive Complexity):

Upvotes: 0

Peska
Peska

Reputation: 4140

Maybe something like this:

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

Upvotes: 9

Related Questions