Reputation: 72
I am not sure if this question should be here or on another community on stackexchange. I have some problem regarding design. Here it is an simplified example of my code.
class Data:
store = {
'key':[]
}
def __init__(self):
self.arg1 = 'value'
self.arg2 = 'value'
def add_to_store(contents):
self.store['key'] += contents
Arguments arg1
and arg2
will always be the same while initializing object of class Data
(not that important). Only store
will change depending on contents of a file.
My dilemma is:
is it better to initialize an object in a for loop and each time working on the new one:
for file_content in files_contents:
d = Data()
d.add_to_store(file_content)
or should I create only one object and add method that will clear my dictionary?
d = Data()
for file_content in files_contents:
d.add_to_store(file_content)
Which is better practice? or it depends and both are correct?
Upvotes: 0
Views: 43
Reputation:
Sharing data across multiple instances is equivalent to having a global variable or singleton. It is considered a bad practice. The second option is better, but you should also use an ordinary dictionary instead of a class attribute. The code:
class Data:
def __init__(self):
self.store = {'key':[]}
self.arg1 = 'value'
self.arg2 = 'value'
def add_to_store(self, contents):
self.store['key'] += contents
# ...
d = Data()
for file_content in files_contents:
d.add_to_store(file_content)
In this case, your Data class is a container for data. It is not a singleton. You can create as many instances of it as you want. Each instance will have its own data. This leads to a more flexible design, better testability, easier maintenance, and fewer bugs in the future due to ambiguous behavior (for example, when changes in one part of the code are inferred to other parts of the code).
And if you want to share this data across your application, you should do it explicitly, by providing the same instance of Data to all parts of your application that need it. You may do it manually or by using some dependency injection framework.
Upvotes: 1