Sobes.tech
Junior — Middle

Do you lean towards using inheritance or composition when designing systems?

sobes.tech AI

Answer from AI

When designing systems, composition is usually preferred over inheritance.

Why?

  • Inheritance creates a rigid hierarchy, which can lead to problems when making changes and complicating the code.
  • Composition allows creating objects from components, making the system more flexible and extensible.

For example, instead of creating a "Bird" class and inheriting "FlyingBird" and "RunningBird" from it, it's better to create a "Bird" class that contains behavior objects (e.g., flying, running). Then, you can dynamically change behavior without altering the hierarchy.

In iOS, protocols and delegates are often used, which is a form of composition.

Example in Swift:

protocol Flyable {
    func fly()
}

class Bird {
    var flyingAbility: Flyable?
    func performFly() {
        flyingAbility?.fly()
    }
}

class CanFly: Flyable {
    func fly() {
        print("I am flying")
    }
}

class CannotFly: Flyable {
    func fly() {
        print("I cannot fly")
    }
}

let sparrow = Bird()
sparrow.flyingAbility = CanFly()
sparrow.performFly() // I am flying

let penguin = Bird()
penguin.flyingAbility = CannotFly()
penguin.performFly() // I cannot fly

Thus, composition provides greater flexibility and simplifies code maintenance.

Do you lean towards using inheritance or composition… - sobes.tech