How can I reduce the complexity of the bellow piece of code? I am getting this error in SonarQube:
Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.
(function () {
window.dm = window.dm || { AjaxData: [] };
window.dm.AjaxEvent = function (et, d, ssid, ad) {
dm.AjaxData.push({
et, d, ssid, ad,
});
window.DotMetricsObj && DotMetricsObj.onAjaxDataUpdate();
};
const d = document;
const h = d.getElementsByTagName('head')[0];
const s = d.createElement('script');
let t = 'inews';
s.type = 'text/javascript';
s.async = true;
if (window.PageContext.categories) {
for (let category of window.PageContext.categories) {
if (Utils.categoryMap[category.slug]) {
t = Utils.categoryMap[category.slug];
break;
}
}
}
if (window.PageContext.post && window.PageContext.post.breadcrumbs) {
for (let category of window.PageContext.post.breadcrumbs.reverse()) {
if (Utils.categoryMap[category.slug]) {
t = Utils.categoryMap[category.slug];
break;
}
}
}
}());
export default () => { };
You can for example extract the complex if blocks to separate methods.
I mean these if blocks:
Extract to method 1 (eg handleCategories):
if (window.PageContext.categories) {
for (let category of window.PageContext.categories) {
if (Utils.categoryMap[category.slug]) {
t = Utils.categoryMap[category.slug];
break;
}
}
}
Extract to method 2 (eg handleBreadcrumbs):
if (window.PageContext.post && window.PageContext.post.breadcrumbs) {
for (let category of window.PageContext.post.breadcrumbs.reverse()) {
if (Utils.categoryMap[category.slug]) {
t = Utils.categoryMap[category.slug];
break;
}
}
}
This will move around 3 complexity levels (if + for + if) from the original method to each of the extracted methods.
SonarQube should be telling you where each complexity point comes from. You'll see the most complexity accrued on those inner if statements. So anything you can do to reduce their complexity count is going to help a lot.
Inverted condition & early return is a favorite tactic of mine. Here's how it can help in this situation:
(function () {
window.dm = window.dm || { AjaxData: [] };
window.dm.AjaxEvent = function (et, d, ssid, ad) {
dm.AjaxData.push({
et, d, ssid, ad,
});
window.DotMetricsObj && DotMetricsObj.onAjaxDataUpdate();
};
const d = document;
const h = d.getElementsByTagName('head')[0];
const s = d.createElement('script');
let t = 'inews';
s.type = 'text/javascript';
s.async = true;
if (!window.PageContext.categories) {
for (let category of window.PageContext.categories) {
if (Utils.categoryMap[category.slug]) {
t = Utils.categoryMap[category.slug];
break;
}
}
}
if (!window.PageContext.post || !window.PageContext.post.breadcrumbs) {
return;
}
for (let category of window.PageContext.post.breadcrumbs.reverse()) {
if (Utils.categoryMap[category.slug]) {
t = Utils.categoryMap[category.slug];
break;
}
}
}());