1

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)
1
  • 1
    There's no circular references here. Though I'm not sure why you're passing transaction=Transaction as a parameter. Nov 2, 2018 at 20:56

1 Answer 1

4

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)

1
  • Well, in the domain, yes, only the Person class can initiate a Transaction. I really think that this design can be improved as I was receiving a very strong "code smell", that's why the question here.
    – cllamach
    Feb 16, 2015 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.