Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Dependency Injection


The Problem: tight coupling between classes

When a class X cannot do its job without class Y, we asy that class X is dependent on class Y

In order to perform this dependenncy many programmers create the object from class Y in the construct of class X. Tight coupling is considered bad practice.

In fact, when we do tight coupling between classes , we violate a fundemental principle of well desinged  code called the "single responisbility principle"(SRP)

According to SRP a class should have only one responsibility.

The Solution: Dependency Injection

When we use dependency injection we pass the object on which our class depends to the class from the outside, instead of creating the objects within the class. By doing so we make our code more maintainable and flexible. It is also advisable to type hint the injected objects in order to make it clear on which type of object does the main class depend although type hinting is not necesary for dependency injection.


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.