DEV Community

Raounak Sharma
Raounak Sharma

Posted on

Dependency Injection | Writing loosely coupled code

In life, we depend on a lot of things to survive. And object-oriented languages that are used to simulate real-world entities in terms of the objects also have dependencies. They have it in terms of one object depending on others. We say that this object is dependent on others when any change in later will force a change in the previous one.

One object depends on other means it knows about it. The former one knows the name of the other object, it's properties and it's behavior. We call such objects tightly coupled i.e two objects are tightly coupled if they know a lot about each other and neither of them can't be reused without using the other one.

Such type of codebase is not good in terms of the reusability of code. One such issue which causes tightly coupled code is referring to other classes directly in methods of a class. This makes the class to work with only that particular class which we have mentioned in the method. We can solve this by dependency injection

Dependency Injection means we explicitly inject dependencies into the new object we are creating.

Always inject your dependencies and never explicitly mention them inside methods.
Consider the following code:

class Bill
  def amount
    total_price(list_product) + Restaurant.new.standard_service_tax
  end

  def total_price(list_product)
    # Return total amount by adding the price of each product
  end
end

The problem with this code is that the Bill class object will only respond to amount behavior if there is a Restaurant class present and implements standard_service_tax behavior. We are not able to reuse this Bill class with another class even though if that has standard_service_tax behavior implemented.

The correct code could be:

class Bill
  attr_reader :service
  def initialize(service: Restraunt.new)
    @service = service
  end

  def amount
    total_price(list_product) + service.standard_service_tax
  end

  def total_price(list_product)
    # Return total amount by adding the price of each product
  end
end

Now we can pass any object to the constructor of Bill, and the amount will work if they have the standard_service_tax behavior implemented.

Summary

Injecting dependencies will make the class loosely coupled and thus increases it's reusability.

Happy Coding 🎉

Top comments (0)