samedi 8 février 2020

How to define an instance depending on some variable?

I'll give code on Python, but it's doesn't matter. I have a module argument_parser with dictionary and class:

FORMATS = {
    'JSON': 'json',
    'XML': 'xml',
}

class ArgumentParser:
    # some methods
    def parse():
        """returns 'XML' or 'JSON' string"""
        return fomat

and a module with presenters -- presenter

class JSONPresenter:
    # some magic


class XMLPresenter:
    # some magic

The problem is in dependency injection:

argument_parser = ArgumentParser()
format = argument_parser.parse()

if format == argument_parser.FORMATS['JSON']:
    presenter = JSONFilePresenter()
elif format == argument_parser.FORMATS['XML']:
    presenter = XMLFilePresenter()

if-elif construction is ugly. If I want to add some other formats I'll must add more elif. I could define the type of presenter in ArgumentParser class but I think semantically it is wrong -- it is not a filed of responsibility of this class. What should I do to do it right?

Aucun commentaire:

Enregistrer un commentaire