reading-notes

Python Random

Readings

Reference

How to Use the Random Module

Dependency Injection

Dependency injection is a software design pattern that allows a programmer to specify the dependencies for a class in a separate location from the class itself. The main idea behind dependency injection is to reduce the tight coupling between software components by allowing the dependencies of a class to be injected at runtime, rather than being hard-coded into the class.

There are several benefits to using dependency injection:

There are several different ways to implement dependency injection, including:

The specific technique used may depend on the programming language and the specific needs of the application.

Example: Constructor Injection

Constructor injection is a common way to implement dependency injection, because it allows the dependencies of a class to be specified when the class is instantiated. This can be especially useful when the dependencies are required for the class to function properly.

Say we have a class called Person that has a dependency on a Car class. We can use dependency injection to specify the Car dependency in a separate location from the Person class itself. In this case, the dependency is injected through the constructor of the class (Person).

  1. Define the Car class
class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model
    
    def drive(self):
        print(f"Driving a {self.make} {self.model}")
  1. Define the Person class with a drive method that has a Car dependency
class Person:
    def __init__(self, car):
        self.car = car
    
    def drive(self):
        self.car.drive()
  1. Can now create an instance of Car and pass it to the Person constructor as a dependency
car = Car("Toyota", "Camry")
person = Person(car)
person.drive()

# Outputs: 'Driving a Toyota Camry'

By using dependency injection, we were able to specify the Car dependency in a separate location from the Person class, which makes it easier to test and maintain the Person class.