vendredi 19 juillet 2019

How do I fix bi-directional dependency between ItemManager and ItemValidator?

I have a bi-directional relationship between two class, ItemManager and ItemValidator, where an ItemManager has a list of ItemValidators but each ItemValidator also takes an instance of the ItemManager it belongs to so that it can use methods from the ItemManager.

Is this bad practice as I can't find a better way to do it.

class ItemValidator:
    def __init__(self, order_manager):
        self.order_manager = order_manager

    def run(self, new_item):
        raise NotImplementedError()


class ItemValidatorImpl(ItemValidator):

    def run(self, new_item):
        existing_items = self.order_manager.list_items()  # Here is the issue as the validator needs methods from the OrderManager
        # ... validate the new item ...


class ItemManager:
    validator_classes = [ItemValidatorImpl]

    def run_validations(self, new_item):
        for validator_class in self.validator_classes:
            validator = validator_class(self)
            validator.run(new_item)

    def list_items(self):  # Method used by some validator implementations
        pass



Aucun commentaire:

Enregistrer un commentaire