Skip to main content
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
edited tags
Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237
Source Link

Reducing cyclomatic complexity in a simple string concatenation

I have written the following function that takes an address object and builds a string using the object properties. It will later be used to display a tooltip

var getAddressTooltip = function (address) {

    var tooltip = '';

    if (address.MasterAddress !== undefined &&
        address.MasterAddress !== null &&
        address.MasterAddress.Id !== undefined &&
        address.MasterAddress.Id !== null) {
        tooltip += '[' + address.MasterAddress.Id + '] ';
    }
    if (address.PurchasingContact !== null &&
        address.PurchasingContact !== undefined &&
        address.PurchasingContact.Name !== null &&
        address.PurchasingContact.Name !== undefined &&
        address.PurchasingContact.Name.length > 0) {
        tooltip += $.trim(address.PurchasingContact.Name) + ',\n';
    }
    if (address.ShipTo !== null && address.ShipTo !== undefined && address.ShipTo.length > 0) {
        tooltip += $.trim(address.ShipTo) + ',\n';
    }
    if (address.Line1 !== null && address.Line1 !== undefined && address.Line1.length > 0) {
        tooltip += $.trim(address.Line1) + ',\n';
    }
    if (address.Line2 !== null && address.Line2 !== undefined && address.Line2.length > 0) {
        tooltip += $.trim(address.Line2) + ',\n';
    }
    if (address.City !== null && address.City !== undefined && address.City.length > 0) {
        tooltip += $.trim(address.City) + ',\n';
    }
    if (address.State !== null &&
        address.State !== undefined &&
        address.State.Name !== null &&
        address.State.Name !== undefined &&
        address.State.Name.length > 0) {
        tooltip += $.trim(address.State.Name) + ',\n';
    }
    if (address.ZIP !== null && address.ZIP !== undefined && address.ZIP.length > 0) {
        tooltip += $.trim(address.ZIP) + ',\n';
    }

    //replace trailing comma / line break
    if (tooltip.substr(tooltip.length - 2, 2) === ',\n') {
        tooltip = tooltip.substr(0, tooltip.length - 2);
    }

    return tooltip;
};

As you can probably tell, I'm rather fastidious about ensuring the values are there before concatenating them, as we have had problems in the past with properties coming back as undefined and bringing the whole application crashing to a halt.

However, the cyclomatic complexity of this function is through the roof because of all the null / undefined / length > 0 checks that I'm doing. It is entirely possible that I'm taking things too far.

What I'm wondering is if anybody knows a faster, smarter and tidier way of doing the same thing? Do I really need all these checks? It appears that if I want valid, safe and linted JavaScript, all of them are necessary.