0

It's said that circular dependencies are bad and anti-patterns. So my question is what's wrong with the code below? Is it an example of circular dependency at all? The code is in python pseudocode but should be understood.

class Manager:
    _handlers = []

    def on_config(self):
        # do something...
        # and notify about "event"
        for handler in self._handlers:
            handler()

    def add_change_handler(self, handler):
        self._handlers.append(handler)

    def get_value(self):
        return some_value

class Consumer:
    def __init__(self, manager):
        self._manager = manager
        self._manager.add_change_handler(self._on_event)

    def _on_change(self):
        print('Got event')

    def do_something(self):
        self._manager.get_value()

So: Consumer gets manager to:

  • get_value from it
  • to register for litening on change event

The argument from guys that are against that solution is that it's better to create other class, that will:

  • know about manager and consumer
  • listen on config event
  • call consumer's on_change handler
  • Consumer will use manager only to get_value
user2146414
  • 840
  • 11
  • 29

1 Answers1

-1

Circular (or cyclic) imports in Python. This answer will help you know more about circular imports in python.

This code is not about circular dependency. You can also regard this situation as a trade between bussinessmans.

#!/bin/python
class Businessman:
    _trader_list = []

    def __init__(self, name, goods):
        self.m_name = name
        self.m_goods = goods

    def on_get_goods(self):
        for trader in self._trader_list:
            trader.buy_some(self)

    def add_change_handler(self, handler):
        self._trader_list.append(handler)

    def del_change_handler(self, handler):
        self._trader_list.remove(handler)

    def buy_some(self, from_bussinessman):
        print "{0} will buy some {1}s from {2}".format(
            self.m_name, from_bussinessman.m_goods, from_bussinessman.m_name)

    def get_goods(self):
        print("{0} gets new {1}s.".format(self.m_name, self.m_goods))
        self.on_get_goods()

if __name__ == "__main__":
    bob = Businessman('Bob', 'apple')
    jack = Businessman('Jack', 'banana')
    cream = Businessman('Cream', 'rice')
    # Bob notifys Jack and Cream to buy apples when he gets some.
    seller1 = bob
    seller1.add_change_handler(jack)
    seller1.add_change_handler(cream)
    seller1.get_goods()

The result is

Bob gets new apples.
Jack will buy some apples from Bob
Cream will buy some apples from Bob
Community
  • 1
  • 1
Jak Liao
  • 146
  • 1
  • 5