I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:
def run(self):
status = False
if step_1():
if step_2():
if step_3():
etc... [several nested IFs]
status = True
else:
self.logger.error('Error in step 3')
else:
self.logger.error('Error in step 2')
else:
self.logger.error('Error in step 1')
return status
Is there a more elegant way (a design pattern?) to avoid these nested IF statements?
Thanks a lot,
解决方案
You would place your steps in a list:
my_plan = (step1, step2, step3, ..., stepN)
And then execute them in a loop:
for step in my_plan:
if not step():
print 'Error in %s' % step.__name__
status = False
break
else:
status = True