I have a class with like 50 methods.
class MyProgram(object):
def method1(self):
pass
def method2(self):
pass
# and so on
Its that big because my Class is also my program, i call myProgram.py via the console and many methods are options like:
myProgram.py --method1 --method2
On the one hand it is really easy for me to use the methods like this. On the other hand the code is just not readable anymore. If I have to change two things, I have to go 1000 lines up and then 2000 lines down to just changes some dependencies or add a new feature like method999().
How can I split my class and still have something like myProgramm.py –method1 –method2 ?
Its important that I can call my program like this to do some cronjobs.
(I’m convinced that there is a really easy solution to this, but I just can’t think about it now)
EDIT: a better example of my god class.
class myprogram(object):
def __init__(self)
self.prepare()
def prepare(self):
# some initializations
self.prepareCommands()
def prepareCommands(self):
self.initCommand("--updateDatabase", self.updateDatabase)
self.initCommand("--getImages", self.getImages)
# and so on
def initCommand(self, cmd, func):
options = sys.argv
for option in options:
if option.find(cmd)!=-1:
return func()
# my commands
def updateDatabase(self):
#...
def getImages(self):
#...
if __name__ == "__main__":
p = myprogram()
EDIT2: After researching a little I think I got a good solution. I will update everything when I’ve rewritten my programm. 🙂
Could you use an extra level of indirection? (This is an old Computer Science axiom:-)
Edit:
So instead of using the actual method names on the command line, use a dictionary to call the actual code. The dictionary maps the command line ‘names’ to the actual function or object+method that gets called. Then you would have more flexibility about code structure.
This is only a small part of a solution. Its ‘usefulness’ is by building the dictionary first, the command line interface is decoupled from the code. Then refactoring the code should be easier, in a test-driven development sense, because the tests and cronjobs won’t have to change as the underlying code is restructured. It gives the flexibility to do the restructuring in an iterative and piecemeal way.
(From the comments, it looks like folks knows how to use a dictionary do this).