Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cyclomatic Complexity Violation: Function should have complexity 10 or less: currently complexity equals 13 (cyclomatic_complexity)

Tags:

I have the following code in swift3 and i am using swift lint for linting the code. The code is given as follows:

    func selectedMenuInLoggedOutState(sender: UIButton) {     switch sender.tag {     case 1:       if let menu = LeftGuestMenu(rawValue: 0) {         self.changeGuestViewController(menu)       }     case 2:       if let menu = LeftGuestMenu(rawValue: 1) {         self.changeGuestViewController(menu)       }     case 3:       if let menu = LeftGuestMenu(rawValue: 2) {         self.changeGuestViewController(menu)       }     case 4:       if let menu = LeftGuestMenu(rawValue: 3) {         self.changeGuestViewController(menu)       }     case 5:       if let menu = LeftGuestMenu(rawValue: 4) {         self.changeGuestViewController(menu)       }     case 6:       if let menu = LeftGuestMenu(rawValue: 5) {         self.changeGuestViewController(menu)       }     default:       break     }   } 

The swift lint generates a "Cyclomatic Complexity Violation" warning. Why did this warning occur and how does one resolve it?

enter image description here

like image 554
Chelsea Shawra Avatar asked Aug 25 '17 23:08

Chelsea Shawra


People also ask

What is cyclomatic complexity violation?

Some of them are extremely easy to address, even by autocorrect; however, some warnings may be harder to remove, for example “Cyclomatic Complexity Violation”. The idea of cyclomatic complexity is very simple: the more branching and jumping logic you have in your code, the more complex your code is.

What is cyclomatic complexity Swift?

Cyclomatic complexity is a measurement developed by Thomas McCabe to determine the stability and level of confidence in a program. It measures the number of linearly-independent paths through a program module.

What cyclomatic complexity is too high?

Consequences: A high cyclomatic complexity for a particular function means that the function will be difficult to understand, and more difficult to test. That in turn means functions with a cyclomatic complexity above 10 or 15 can be reasonably expected to have more undetected defects than simpler functions.

What is cyclomatic complexity in software testing?

Cyclomatic Complexity Measures The Cyclomatic complexity defines the number of independent paths in the basis set of the program that provides the upper bound for the number of tests that must be conducted to ensure that all the statements have been executed atleast once.


1 Answers

The method is too complex. But instead of rewriting the code, you could exclude switches from the cyclomatic_complexity calculation (since they are perfectly readable) like this:

cyclomatic_complexity:   ignores_case_statements: true 
like image 131
Jakub Truhlář Avatar answered Oct 12 '22 14:10

Jakub Truhlář