0

I met warning like this "Cyclomatic Complexity Violation: Function should have complexity 10 or less: currently complexity equals 14 (cyclomatic_complexity)" when I used RxDataSource.

My code structure like this:

struct ItemDetailDataSource {
    typealias DataSource = RxTableViewSectionedReloadDataSource
    
    static func dataSource() -> DataSource<ItemDetailTableViewSection> {
        return .init(configureCell: { (dataSource, tableView, indexPath, _) -> UITableViewCell in
            
            switch dataSource[indexPath] {
            case .itemInfoTopItem(let info):
                guard let cell = tableView.dequeueReusableCell(withIdentifier: ConstantsForCell.infoTopTableViewCell,
                                                               for: indexPath)
                    as? InfoTopTableViewCell else {
                        return UITableViewCell()
                }
                cell.configure(info)
                return cell
            case .itemHintItem(let hint):
            ...
            case .itemManaColdownItem(let manacd):
            case .itemNotesItem(let notes):
            case .itemAttribItem(let attrib):
            case .itemLoreItem(let lore):
            case .itemComponentsItem(let components):
}

enter image description here

Can anyone help me fix this? Thanks very much.

hhg
  • 79
  • 1
  • 6
  • 2
    Cyclomatic complexity goes up with every control statement (for, if, case, etc.). This is really more of a code review question. You can also research how to reduce cyclomatic complexity. – General Grievance Dec 08 '21 at 15:38
  • thank you very much, I have researched this quite many times but perhaps it's too hard for me :((( – hhg Dec 09 '21 at 02:58

1 Answers1

1

The solution here is to not use an enum for your cell items. A possible solution is as follows:

struct DisplayableItem {
    let makeCell: (UITableView, IndexPath) -> UITableViewCell
}

struct ItemDetailDataSource {
    typealias DataSource = RxTableViewSectionedReloadDataSource
    
    static func dataSource() -> DataSource<ItemDetailTableViewSection> {
        .init { _, tableView, indexPath, item in
            item.makeCell(tableView, indexPath)
        }
    }
}

Each DisplayableItem is given the means for making a UITableViewCell. You could do it with a closure like above, or with a protocol and a bunch of sub-classes.

Daniel T.
  • 32,821
  • 6
  • 50
  • 72