I am trying to make an example of Strategy design pattern in Python 3.x. Below is my code. I feel like this can be improved but I don't know how. The
run methods seem to take more responsibilities for testing and executing. So does
__init__ function. The class takes an external function to create an object but also:
- checks if input arguments for the function
- loads an object if exists to avoid re-calculations
- checks if user wants to create an object regardless conditions
- tests if an object to return is None
- returns an object.
I am wondering how this can be improved. This is the code:
class Strategy(object): def __init__(self, filename, forcecreate=False): if (filename is None) or (not isinstance(filename, str)) or (filename == ""): raise ValueError("File name is not set") self.filename = filename self.forcecreate = forcecreate self.t = None self.output = None def run(self, process, *inputs): if not self.forcecreate: self.output = self.__pre() if not self.output is None: return self.output # Check if objects provided are defined if len(inputs) > 0: if any([i is None for i in inputs]): raise ValueError("One of the objects is not set") self.output = process(*inputs) self.__post() return self.output def __pre(self): if (Path(self.filename).is_file()): print("File exists") with open(self.filename, 'rb') as f_handler: return pickle.load(f_handler) return None def __post(self): with open(self.filename, 'wb') as f_handler: pickle.dump(self.output, f_handler)
I have a set of functions which process data and return objects which contain some structured data. I also save objects in order to avoid re-calculations. If a file exists, I can just load an object and return it. The number of functions is getting higher and I end up with copy-pasting. I thought that would slightly improve my code.