Advanced Object-Oriented Programming in Kotlin

May 22 2024 · Kotlin 1.9, Android 14, Kotlin Playground

Lesson 04: Liskov Substitution, Interface Segregation & Dependency Inversion

Implementing Dependency Inversion Principle

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Dependency Inversion states that high-level modules shouldn’t depend on low-level modules but on abstractions. In this demo, you’ll adhere to this principle to reduce coupling in your e-commerce app.

Processing order...
Persist order amounting to 2400.0 to an SQLite Database.
interface OrderRepository {
  fun saveOrder(shoppingCart: ShoppingCart): Boolean
}
class SqliteOrderRepository : OrderRepository {
  override fun saveOrder(shoppingCart: ShoppingCart): Boolean {
    println("Persist order amounting to ${shoppingCart.getTotalOrderPrice()} to an SQLite Database.")
    return true
  }
}
class OrderService(private val orderRepository: OrderRepository) {
  fun processOrder(shoppingCart: ShoppingCart) {
    println("Processing order...")
    orderRepository.saveOrder(shoppingCart)
  }
}
val orderProcessor = OrderService(SqliteOrderRepository())
Processing order...
Persist order amounting to 2400.0 to an SQLite Database.
class InMemoryOrderRepository : OrderRepository {
  override fun saveOrder(shoppingCart: ShoppingCart): Boolean {
    println("Persist order amounting to ${shoppingCart.getTotalOrderPrice()} to an In-Memory Database.")
    return true // success
  }
}
val orderProcessor = OrderService(InMemoryOrderRepository())
orderProcessor.processOrder(shoppingCart)
Processing order...
Persist order amounting to 2400.0 to an In-Memory Database.
See forum comments
Cinema mode Download course materials from Github
Previous: Learning Dependency Inversion Principle Next: Conclusion