0

Suppose I have requirement to draw a shape. The shape will be decided by backend server. I have following code:

enum ShapeType {
    case circle
    case rectangle
}

protocol Shape {
    var type: ShapeType { get }
    func render()
}
    
struct Circle: Shape {
    let type: ShapeType = .circle
    
    func render() {
        print("Draw Circle")
    }
}

struct Rectangle: Shape {
    let type: ShapeType = .rectangle
    
    func render() {
        print("Draw Rectangle")
    }
}

my current logic to select a shape to draw is:

if serverShapeString == "Circle" {
    let circleShape: Shape = Circle()
    circleShape.render()
} else {
    let rectangleShape: Shape = Rectangle()
    rectangleShape.render()
}

I have written the protocol and the enum. If any new shape comes I will write separate class for it but still don;t get how to avoid if else based on the serverShapeString. I have to avoid that if else because it keeps on increasing as we have more shapes.

Bhushan B
  • 2,470
  • 4
  • 26
  • 38
  • `I have to avoid that if else because it keeps on increasing as we have more shapes`. How many shapes do you have now? – Adam Jenkins May 24 '22 at 11:31
  • Note: SOLID principles are principles of Object-oriented design. This is not Object-oriented. You say "any new shape comes I will write separate class" but there are no classes in your code. – Shadowrun May 24 '22 at 11:34
  • 1
    The series of `if` statements is essentially unavoidable. You need to map a string to an implementation. You can use a *factory* pattern to hide this code so that you essentially have a function that accepts a string and returns a `Shape`. A `Shape` is an abstraction that you can ask to `render`; there is no need to repeat the `render` call within each clause, however you need to consider that in reality the different shapes require different initialisers; a rectangle has a width & height while a circle has a radius. – Paulw11 May 24 '22 at 11:45
  • 1
    @Shadowrun that seems a little nit-picky. There are structs and protocols, which are elements of Swifts object orientation. The use of classes is not mandatory. – Paulw11 May 24 '22 at 11:47
  • 1
    You can't avoid if else in this scenario. Bcz its totally conditional and also your input is String so you'll have to use If else. If input were type `Shape` then could manage it – Kudos May 24 '22 at 11:47
  • Structs and protocols are not related to object-oriented programming. They pertain more to functional/protocol-oriented programming styles than OOP. It's a worthwhile distinction to consider, because best practices in different programming styles are different, SOLID is for OOP. It's not meant to be a nit pick. Structs/protocols/enums are not objects, and if you don't have objects you're definitely not doing OOP. – Shadowrun May 24 '22 at 11:56

0 Answers0