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

Chelsea Shawra picture Chelsea Shawra · Aug 26, 2017 · Viewed 19.8k times · Source

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

Answer

Jakub Truhlář picture Jakub Truhlář · Jul 7, 2018

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