Home > OS >  Refactor a switch statement with cyclomatic complexity
Refactor a switch statement with cyclomatic complexity

Time:03-16

Currently i am getting the warning "Cyclomatic Complexity Violation: Function should have complexity 8 or less: currently complexity equals 9 (cyclomatic_complexity)"

I want to refactor it so it doesn't show the warning anymore

My code is below


CodePudding user response:

if you just want to ignore the error message, you can use this line in .swiftlint.yml. But on the other hand you can prefer switch case and enum structure for functions in postImageViewModel.

# .swiftlint.yml
 cyclomatic_complexity: 20

CodePudding user response:

How about this?

func tapNext(_ sender: UIBarButtonItem) {
    if let viewModel = postImageViewModel {
        viewModel.tappedNext()
        var availableTap: Bool = true
        
        if viewModel.checkEmpty() {
            viewModel.setImage(true)
            availableTap = false
        }
        
        if viewModel.checkHeadline() {
            viewModel.setHeadline(true)
            availableTap = false
        }
        
        if viewModel.checkMenu() {
            viewModel.setMenu(true)
            availableTap = false
        }
        
        if viewModel.checkLength() {
            viewModel.setLength(true)
            availableTap = false
        }
        
        if viewModel.checkGender() {
            viewModel.setGender(true)
            availableTap = false
        }
        
        if viewModel.isMaxError || viewModel.isDetailMaxError {
            availableTap = false
        }
    }

    if isTagsError {
        availableTap = false
    }

    let isProcessing = postImageViewModel?.checkProcessing() ?? false
    if availableTap && !isProcessing {
        postImageViewModel?.setHeadline(false)
    } else if !availableTap { 
        // 
    } else {
        //
    }
}
  • Related