vendredi 18 octobre 2019

Where to reveal data type in Python factory

let's say that we have to write an api which fetches data from core functionality. I'll show what I mean by the simplified version of the core functionality:

def type_of_data(url):
    # do something_with_url and return type


class Abstract:

    @abc.abstractmethod
    def load(self, data_url):
        raise NotImplementedError("implement")


class LoadInt(Abstract):

    def load(self, data_url):
        return int(data_url)


class LoadString(Abstract):

    def load(self, data_url):
        return str(data_url)


def loader_factory(data_url):

    if type_of_data(data_url) == "str":
        return LoadString()
    elif type_of_data(data_url) == "int":
        return LoadInt()
    raise ValueError("Invalid data type")

And the only thing that user sees here is following method:

### API ###
def get_data(data_url):

   loader = loader_factory(data_url)
   return loader.load(data_url)

The return value of the get_data function will be either int or str (or any other value that might exist in the factory).

Given the fact that the user should know what type of URL it is (string, int, or other) should I just make methods that retrieve specific types of data in API part of the code?

Or should I completely leave the responsibility to users in this case by forcing them to do something like:

value: int = get_data(some_url)

Aucun commentaire:

Enregistrer un commentaire