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 Interface Segregation 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

The Interface Segregation Principle states that code shouldn’t be forced to have methods it doesn’t need. Whenever a class implements an interface, it has to implement all its methods. What do you do when a new class appears to need some of the behaviors defined in an interface but not all? In this demo, you’ll learn how to solve this problem in your e-commerce app.

Parent account viewing products...
Product added to the cart (Parent): Laptop
Parent account viewing cart...

Kids account viewing products...
Product added to the cart (Kids): Laptop
Kids account viewing cart...
interface ProductsViewable {
  fun viewProducts()
}

interface CartViewable {
  fun viewCart()
}

interface CartAddable {
  fun addToCart(product: Product)
}
class KidsAccount : ProductsViewable, CartViewable, CartAddable {
  override fun viewProducts() {
    println("Kids account viewing products...")
  }

  override fun addToCart(product: Product) {
    println("Product added to the cart (Kids): ${product.name}")
  }

  override fun viewCart() {
    println("Kids account viewing cart...")
  }
}
interface PaymentSettingsManageable {
  fun managePaymentSettings()
}
class ParentAccount : ProductsViewable, CartViewable, CartAddable, PaymentSettingsManageable {
  override fun viewProducts() {
    println("Parent account viewing products...")
  }

  override fun addToCart(product: Product) {
    println("Product added to the cart (Parent): ${product.name}")
  }

  override fun viewCart() {
    println("Parent account viewing cart...")
  }

  override fun managePaymentSettings() {
    println("Parent account managePaymentSettings...")
  }
}
// TODO: Uncomment manage payment settings behavior
parentAccount.managePaymentSettings()
Parent account viewing products...
Product added to the cart (Parent): Laptop
Parent account viewing cart...
Parent account managePaymentSettings...

Kids account viewing products...
Product added to the cart (Kids): Laptop
Kids account viewing cart...
See forum comments
Cinema mode Download course materials from Github
Previous: Learning Interface Segregation Principle Next: Learning Dependency Inversion Principle