I am using SonarLint for Eclipse since recently, and it helped me a lot. However, it raised to me a question about cyclomatic complexity.
SonarLint considers as acceptable a C.C of 10, and there are some cases where I am beyond it, about 5 or 6 units. Those parts are related to mappers where the values relies on different variables, for example:
- Field A relies on String sA;
- Field B relies on String sB;
- Field C relies on String sC;
- etc …
I have no other choice that putting an if
for each field. This is not my choice (fortunately) but an already existing and complex system that I cannot change by myself.
The core of my question is: why is it so important to not have a too high C.C in a single method ? If you move some of your conditions in one or more sub-methods to reduce the complexity, it does not reduce the cost of your overall function, it is just moving the problem elsewhere, I guess ?
(Sorry for small mistakes, if any).
EDIT
My question does not refer to global cyclomatic complexity, but only to single method complexity and method splitting (I have a rough time explaining what exactly I mean, sorry). I am asking why does it is allowable to split your conditions into smaller methods if it still belongs to a 'super method', which will just execute every sub-method, thus adding complexity to the algorithm.
The second link however (about the anti-pattern) is of great help.
Best Answer
The core thing here: "brain capacity".
You see, one of the main functions of code is ... to be read. And code can be easy to read and understand; or hard.
And having a high CC simply implies a lot of "levels" within one method. And that implies: you, as a human reader will have a hard time understanding that method.
When you read source code, your brain automatically tries to put things into perspective: in other words - it tries to create some form of "context".
And when you have a small method (with a good name) that only consists of a few lines, and very low CC; then your brain can easily accept this "block". You read it, you understand it; DONE.
On the other hand, if your code has high CC, your brain will spend many many "cycles" more to deduct what is going on.
Another way of saying that: you should always lean towards preferring a complex network of simple things over a simple network of complex things. Because your brain is better at understanding small things.