Reputation: 335
I have been working on refactoring of the entire codebase for one of the project. Basically modularizing the code into separate modules, classes with single responsibilities, breaking the spaghetti function into small small methods etc.
However, I want to know how can we cleanly/elegantly handle the below block of code which has multiple if conditions with continue statements. Idea is to make it smaller and clean. For other cases, I am using predicate wherever I am finding multiple if-and statements. But here the case is little different since they are printing different log messages with respect to different conditions.
def somefunc(*args, **kwargs):
for p_key, p_det in somedict.iteritems():
get_all_somevars(p_det)
if somevar1 and somevar2 is None:
continue
if somevar3 is None:
logger.info('some message')
continue
if somevar4 is None:
logger.info('some message')
continue
somevar5 = x.split('\n')
somevar6 = y.split('\n')
somevar7 = do_something_2(somevar5, somevar6)
if somevar7 is None:
logger.info('some message')
continue
do_something_3()
Upvotes: 3
Views: 1354
Reputation: 2059
Some quality code review rejects multiple continue (more than 2 for example) inside loops.
When it occurs, you can wrap all these conditional into a separate method that will return true / false and log accordingly.
I don't know other way to clean up.
Edit : (pseudo-code)
def somefunc(*args, **kwargs):
for p_key, p_det in somedict.iteritems():
do_something_1()
if should_skip_that_loop(args)
continue
somevar5 = x.split('\n')
somevar6 = y.split('\n')
somevar7 = do_something_2(somevar5, somevar6)
if somevar7 is None:
logger.info('some message')
continue
do_something_3()
def should_skip_that_loop(*args, **kwargs):
if somevar1 and somevar2 is None:
return True
if somevar3 is None:
logger.info('some message')
return True
if somevar4 is None:
logger.info('some message')
return True
return False
Upvotes: 2