Home > Blockchain >  Replace switch cases to reduce complexity
Replace switch cases to reduce complexity

Time:11-29

I wanted to replace switch cases with some other logic since it increases code complexity (CCN) on sonar.

enum ItemType {
    case one, two, three, four, five, six, seven, eight, nine, ten
} 
func handleNavigation(itemType: ItemType){
    switch itemType {
    case .one:
        self.performSegue(withIdentifier: StoryboardSegue.One, sender: nil)
    case .two:
        self.performSegue(withIdentifier: StoryboardSegue.Two, sender: nil)
    case .three:
        self.performSegue(withIdentifier: StoryboardSegue.Three, sender: nil)
    case .four:
        self.performSegue(withIdentifier: StoryboardSegue.Four, sender: nil)
    case .five:
        self.performSegue(withIdentifier: StoryboardSegue.Five, sender: nil)
    case .six:
        self.performSegue(withIdentifier: StoryboardSegue.Six, sender: nil)
    case .seven:
        self.performSegue(withIdentifier: StoryboardSegue.Seven, sender: nil)
    case .eight:
        self.performSegue(withIdentifier: StoryboardSegue.Eight, sender: nil)
    case .nine:
        self.performSegue(withIdentifier: StoryboardSegue.Nine, sender: nil)
    case .ten:
        self.performSegue(withIdentifier: StoryboardSegue.Ten, sender: nil)
    }
}

We have to avoid this switch case since it increases CCN when number of cases increase.

How can we replace switch cases with other logic?

CodePudding user response:

Remove the named constants in StoryboardSegue. Use the enum raw value instead.

First, give ItemType raw values by adding : String

enum ItemType: String {
    case one, two, three, four, five, six, seven, eight, nine, ten
} 

Now you can do:

self.performSegue(withIdentifier: itemType.rawValue, sender: nil)

This will perform segues with identifiers "one", "two", "three" etc.

If your segue identifiers have slightly different identifiers from the names of the enum cases, you can write a transformation function. For example, if they all end with "Segue".

func segueIdentifier(for itemType: ItemType) {
    itemType.rawValue   "Segue"
}

// ...

self.performSegue(withIdentifier: segueIdentifier(for: itemType), sender: nil)

If the identifiers are completely different from the enum case names, then you can use a dictionary:

enum ItemType: Hashable {
    case one, two, three, four, five, six, seven, eight, nine, ten
}

let segueIdMapping: [ItemType: _] = [
    .one: StoryboardSegue.One,
    .two: StoryboardSegue.Two,
    .three: StoryboardSegue.Three,
    // and so on
]

// ...

self.performSegue(withIdentifier: segueIdMapping[itemType]!, sender: nil)
  • Related