I have an if statement set up like this
if (A && B) {
// do something 1
} else {
if (B) {
// set some boolean to false
}
// do something 2
}
I'm wondering if I can lower the cognitive complexity? Right now this is a score of 4.
I have an if statement set up like this
if (A && B) {
// do something 1
} else {
if (B) {
// set some boolean to false
}
// do something 2
}
I'm wondering if I can lower the cognitive complexity? Right now this is a score of 4.
On
Well you could have only one level of depth like this:
function originalImplementation(A, B) {
if (A && B) {
console.log("do something 1");
} else {
if (B) {
console.log("set some boolean to false");
}
console.log("do something 2");
}
}
function newImplementation(A, B) {
if (A && B) {
console.log("do something 1");
}
else if (B) {
console.log("set some boolean to false");
}
if (!A || !B) {
console.log("do something 2");
}
}
console.log("originalImplementation");
originalImplementation(0, 0);
originalImplementation(0, 1);
originalImplementation(1, 0);
originalImplementation(1, 1);
console.log("newImplementation");
newImplementation(0, 0);
newImplementation(0, 1);
newImplementation(1, 0);
newImplementation(1, 1);
On
Setting the boolean first can setup a clearer if/else
if(!A && B) {
// set some boolean to false
}
if (A && B) {
// do something 1
} else {
// do something 2
}
Another strategy is to drop out of functions asap
e.g.
if(X) {
// do stuff
return;
}
if(Z)
{
// do different stuff
return;
}
// do default stuff
return;
This allows the reader to dismiss logic beyond the condition they are interested in
Finally you can also create functions with meaningful names rather than comments
if(X) {
return doSomething2();
}
On
Assuming you do one and only one thing for each case you can try decluttering the syntax:
if statements don't need the curly bracesif, else if, etc. with an early returnconst run = (a, b) => {
if (a && b) return fun1();
if (a) return fun2();
if (b) return fun3();
return fun4();
}
In this case I prefer using nested ternaries. Something usually considered as "bad practice" by tool makers and opinion leaders in the industry but I think with the right indentation they offer more decluttering opportunities:
const run = (a, b) =>
( a && b ? fun1()
: a ? fun2()
: b ? fun3()
: fun4());
Of course YMMV ;)
I would say the best way to lower the cognitive complexity is to use functions. This is similar to @GuerricP original answer, but handles the multiple case of
do somthing 2eg.
This reduces complexity, because it's not obvious that there are 2 routes to doSomething2 in your original version.