DEV Community

Kaziu
Kaziu

Posted on

1 1

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay