mike01010
mike01010

Reputation: 6068

Multiple DAL design pattern

I am relatively new to python. I am building a system that will initially fetch data from a database, but at some point in the future, we’ll be getting the data from a service. To account for this I created an abstract base class called BaseDAL which defines my data getters:

class BaseDAL(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def get_securities(self):
        pass

    @abstractmethod
    def get_security_data(self, ticker):
        pass

The idea here is that the initial concrete implementation will fetch from the database, but when the service is ready, I’ll simply create another concrete implementation that fetches from that service.

Is this the proper design/solution for this type of problem?

Second, what is a good way of conditionally instantiating the concrete provider based on say a class name read from a config file. I imagine something like this..but need help with how I would instantiate the instance from a string name:

class DALFactory(object):
    """reads a config file, creates a concrete provider, and always return that instance"""

    __provider = None
    def __init__(self):
        pass

    @classmethod
    def get_provider(cls):
        if cls.__provider is None:
            cls.__provider = get_provide_type_from_config()

        return cls.__provider

Upvotes: 1

Views: 724

Answers (1)

Patrick Collins
Patrick Collins

Reputation: 10594

It looks like you're a Java programmer. Design patterns, abstract methods, and complex inheritance hierarchies are virtually unknown in Python: because of duck typing, there is no compelling reason to have your other DAL* classes inherit from BaseDAL -- sibling classes with appropriately-named methods get the job done just as well, with less verbosity.

Getters and setters are also basically unused: just access the actual property you want instead. If you later need to refactor it into a method, you can use @property on the method and nothing needs to change.

Simple is better than complex.

EDIT: If DBDal and WSDal are your two classes, you can make a simple "factory" like this (taking advantage of first class functions):

def make_dal(name):
    return {
        'DBDal identifier string': DBDal,
        'WSDal identifier string': WSDal
    }[name]()

Upvotes: 1

Related Questions