mardi 2 février 2021

Alternative pattern to switch statement with enum and if statement for many different cases

In my app i have a class initialized like so, for the sake of the examples down below let's say it is called MyClass and it inherits from UIView:

private let someName: String

init(someName: String) {
    self.someName = someName
    super.init(frame: UIScreen.main.bounds)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Depending on the value of someName after it is initialized, i want to perform total different setups like in the example down here. Right now i'm doing it using an if statement:

if someName == "familyName" {
   self.backgroundColor = .red 
} else if someName == "givenName" {
   self.addSubview(UIImageView(frame: .zero))
} else if someName == "noName" {
   let textView = UITextView()
   self.addSubview(textView)
   textView.text = "This is a text view."
}

Although it works, it seems to me like a bad practice for readability and scalability. When i learnt Swift, i was told it is preferable to avoid an if statement if the cases are more than 3.

So i'm searching for a better pattern to implement.

The trivial solution is to have a different class for each case, but this also looks bad to me, not sure.

A decent way of doing it is to create an enum and pass it in as an initializer, then switching on it with a switch statement.

But, as a beginner who is still learning Swift, i'm wondering if there is a better approach, considering readability and scalability, for achieving what i want than using a switch/if statement, as i read that enum are considered by some an anti-pattern.

Aucun commentaire:

Enregistrer un commentaire