Sobes.tech
Junior — Middle

Can you show how the L principle from SOLID is applied in practice?

sobes.tech AI

Answer from AI

The L principle from SOLID is the Liskov Substitution Principle. It states that objects of subclasses should be interchangeable with objects of the base class without affecting the correctness of the program.

Example in Kotlin:

open class Bird {
    open fun fly() {
        println("Bird is flying")
    }
}

class Sparrow : Bird() {
    override fun fly() {
        println("Sparrow is flying")
    }
}

class Ostrich : Bird() {
    override fun fly() {
        throw UnsupportedOperationException("Ostrich can't fly")
    }
}

fun makeBirdFly(bird: Bird) {
    bird.fly()
}

fun main() {
    val sparrow = Sparrow()
    val ostrich = Ostrich()

    makeBirdFly(sparrow)  // Works correctly
    makeBirdFly(ostrich)  // Violates the Liskov principle, as ostrich can't fly
}

In this example, the Ostrich class violates the L principle because it does not support the behavior of the base class Bird. To adhere to the principle, the hierarchy should be designed so that subclasses fully support the contract of the base class, for example, by separating flying and non-flying birds into different hierarchies.