DEV Community

Kaziu
Kaziu

Posted on

SOLID : Dependency Inversion

When I searched about it, it turned out Dependency Inversion is accomplished by using Dependency Injection

So I'm gonna use my own code about Dependency Injection. Please take a look at first this article, if you haven't read it yet

▼ Bad code in this article of Dependency Injection

class Woman {
  makeLover(){
    const bf = new CrazyMan()
    bf.stayWith()
  }
}

class CrazyMan {
  stayWith() {
    console.log('I am dangerous man, stay with me')
  }
}

const woman = new Woman()
woman.makeLover()
Enter fullscreen mode Exit fullscreen mode

image is like this. Woman depends on Crazy man

Image description

We need to invert this direction, but how?
It resolves by using interface, this is Dependency Inversion

class Woman {
  constructor(man: IMan) {
    this.man = man
  }
  makeLover(){
    this.man.stayWith()
  }
}

// ⭐⭐ this interface is key !!!!!!!
interface IMan {
  stayWith: () => void
}

class CrazyMan {
  stayWith() {
    console.log('I am dangerous man, stay with me')
  }
}

class GoodMan {
  stayWith() {
    console.log('I am good man, stay with me')
  }
}

const man = new GoodMan()
const woman = new Woman(man)
woman.makeLover()

// I am good man, stay with me
Enter fullscreen mode Exit fullscreen mode

▼ Now Crazy man, Good man depend on Man Interface, as you can see direction inverts now

Image description


ref
https://khalilstemmler.com/articles/tutorials/dependency-injection-inversion-explained/
This is good sample of Typescript, it's in japanese though

Top comments (0)