Using private methods for decreasing CC by refactoring some decision points into separate methods decreases the CC of the actual method and eases reading, but does not decrease the effort to get full branch coverage in testing.
Is this justifyable? What is you field experience?
Generally to reduce the cyclomatic complexity you have to reduce the number of possible paths. You can achieve it : by avoiding not required else. grouping condition statements that are separated while it could be a single statement that.
Avoid use of switch/case statements in your code. Use Factory or Strategy design patterns instead. Complexity of 8 (1 for each CASE and 1 for method itself). Refactoring using Factory design pattern and complexity changed to 1.
In short: complexity is difficult to measure. Like all of the methods listed above, Cyclomatic Complexity is not a perfect method of calculating how “complex” or “good” code is, however it is an interesting metric to understand and keep in mind.
Well if you're still interested there is this article I wrote down on Cyclomatic Complexity
Cutting your code in different methods won't reduce the complexity but will only help locally to have a better organisation. The only real way to reduce CC is to refactor indeed !
You will need the same amount of tests if you only extract methods. Have a look at you're data structures may be they're not helping you ? Consider cutting in several classes too if it has sens.
Sometimes, making your application code less complex and more readable has as a consequence that your test code becomes more complex and less readable. However, that is not a reason not to do the refactoring. Readability of the production code is more important than your tests.
If you make some methods private for decreasing CC and improving readability, you could use a framework like Mockito to still be able to test the private methods themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With