Having too many return statements in a function increases the function’s essential complexity because the flow of execution is broken each time a
return statement is encountered. This makes it harder to read and understand the logic of the function.
The way of counting the return statements is aligned with the way we compute Cognitive Complexity.
"Under Cyclomatic Complexity, a switch is treated as an analog to an if-else if chain […] but from a maintainer’s point of view, a switch -
which compares a single variable to an explicitly named set of literal values - is much easier to understand than an if-else if chain because the
latter may make any number of comparisons, using any number of variables and values. "
As a consequence, all the return statements located at the top level of case statements (including default) of a same switch statement count all
together as 1.
// this counts as 1 return
int fun() {
switch(variable) {
case value1:
return 1;
case value2:
return 2;
default:
return 3;
}
}
Noncompliant code example
With the default threshold of 3:
// this counts as 3 returns
int fun() {
if (condition1) {
return 1;
} else {
if (condition2) {
return 0;
} else {
return 1;
}
}
return 0;
}
// this counts as 3 returns
int fun() {
switch(variable) {
case value1:
if(condition1) {
return 1;
} else {
return -1;
}
default:
return 2;
}
}