This is probably a very common question, but has not yet found a suitable answer.
I have (Python w / C ++ modules) an application that actively uses the SQLite database, and its path is provided by the user when the application starts.
Every time some part of the application needs access to the database, I plan to purchase a new session and cancel it when it is done. To do this, I clearly need access to the path specified at startup. A couple of ways that I see this happening:
1. Explicit arguments
The database path is passed wherever it must be through an explicit parameter, and the database session is created using this explicit path. This is perhaps the most modular, but it seems incredibly inconvenient.
2. The path to the singleton database
The database session object will look like this:
import foo.options class DatabaseSession(object): def __init__(self, path=foo.options.db_path): ...
I believe that this is a singleton of lesser evil, since we only keep constant lines that do not change at runtime. This allows you to override the default class and unit test DatabaseSession if necessary.
3. Database path singleton + static factory
Perhaps a slight improvement over the above:
def make_session(path=None): import foo.options if path is None: path = foo.options.db_path return DatabaseSession(path) class DatabaseSession(object): def __init__(self, path): ...
Thus, the module does not depend on foo.options at foo.options , unless we use the factory method. In addition, a method can do things such as session caching or something else.
And then there are other patterns that I don't know about. I vaguely saw something like this in web frameworks, but I have no experience with them. My example is quite specific, but I assume that it also expands to other application parameters, hence the message header.
I would like to hear your thoughts on what would be the best way to organize this.