Prompted by Sonar, I am looking to reduce the complexity of a function (one that some might call arrow code). I am loosely familiar with some of the principles of reducing arrow code complexity (flattening, eager returns, guard statements instead of affirmative condition checks), but I doubt that this particular code is satisfied by any of those.
The function takes three parameters and returns a string. If the first parameter does not meet the criteria for if/else-if outer block, the function returns a default string (the initial string assignment). For the sake of brevity, I think we can safely assume the function takes only 2 parameters.
Pseudocode
String getMyString(String parameter1, String parameter2) {
String myString = "STRING_A.Y"
if (parameter1 == optionA) {
if (parameter2 == optionX) {
myString = "STRING_A.X"
} else {
myString = "STRING_A.Y"
}
} else if (parameter1 == optionB) {
if (parameter2 == optionX) {
myString = "STRING_B.X"
} else {
myString = "STRING_B.Y"
}
}
return myString
}
In the case of three parameters, we are looking at 8 possible outputs. The only way I see to "reduce" complexity would be to turn this into a switch statement, but I personally find that the code would be less readable (particularly when more parameters are introduced). I don't see a meaningful way to separate this code into smaller functions. I don't see a way to add guard statements that might reduce the degree of nesting here. Is a switch statement the best alternative?
A.X,A.Y, B.X,B.Y, O
. Ah well, analyzing cyclomatic complexity is hardly my forte. I tend to not be that zoomed in to care about these things quite as much (more concerned with integration than units at my zoomed-out level). But there is an obvious duplication of logic in the inner branches which sticks out to me and implies more things to test and could go wrong at a glance level...