Circular Dependency Injection in Python – Best Practices and Risks

code-qualitydependency-injectionpython

I'm trying the Dependency Injection pattern in some new classes, more specifically in a Transaction System and stumbled into a dilemma. I have a Person class with a create_new_transaction method, and a Transaction class to represent my each transaction.

As the pattern dictates I inject the class transaction in the constructor. But I also wanted to inject the originator and receiver objects into the Transaction class so I can access their public name and account parameter. Am I hurting the design by implementing this? Is this creating high coupling between these two classes?

class Transaction(object):

      def __init__(self, amount, from_person, to_person):
          self.from = from_person
          self.to = to_person


class Person(object):

     def __init__(self, name, transaction=Transaction):
         self._transaction = transaction
         self.name = name

     def create_new_transaction(self, amount, destiny):
         return self._transaction(amount, from_person=self, to_person=destiny)

Best Answer

Whenever someone says 'Circular Dependency' I shudder. I see as an issue on the design. DI is independent of circular dependency.

You are indeed creating coupling between the two classes. Is it needed? As a general case, I don't believe so. I think that you are giving too much responsibility to the Person class. Therefore, you are hurting the design. Can only Person initiate transactions? Will at any point a different entity be the source or destination of a transaction (e.g., a company)?

It will depend on what are the exact requirements and the domain in which you are working. But I would have something else creating the transaction (Bank class, or Dealer class, or something like that)

Related Topic