I'd like to eliminate constructor business logic in class, but force initialization of the object before it can used by the client.
Simple example:
In this case I want to create an object for manipulating only one ini file in its lifetime. I read the configs in the constructor so when the object is instantiated the client can immediately use them.
import configparser
import os
class ConfigParserWrapper(object):
def __init__(self, ini_file_path: str) -> None:
if not os.path.isfile(ini_file_path):
raise FileNotFoundError("Ini file is not found!")
self._ini_file_path = ini_file_path
self.__config = configparser.RawConfigParser()
self.__config.read(ini_file_path)
def modify_configs(self, section, option, value):
...
def clear_configs(self, section, option):
...
def save_configs(self):
...
I can place the logic to a new method.
class ConfigParserWrapper(object):
def __init__(self, ini_file_path: str) -> None:
self._ini_file_path = ini_file_path
def read_configs(self):
if not os.path.isfile(self._ini_file_path):
raise FileNotFoundError("Ini file is not found!")
self.__config = configparser.RawConfigParser()
self.__config.read(self._ini_file_path)
But in this case the client needs to call the method after the instantiation.
I don't want to create and pass the RawConfigParser object to the constructor directly (or by using setters) from the client's module.
Is it worth it to implement a builder to do the instantiation and initialization in this case or do you know any other useful pattern/technique to this?
Thanks!
Aucun commentaire:
Enregistrer un commentaire