A method grew too big for its own good, and I need to break it up into two separate methods.
def big_method(dct):
# Initial code
# ...
for i in dct:
# More code
# ...
for j in dct[i]:
# Inner code
# ...
# ...
# and a break
if j == 'something':
break
# Inner code ended here.
The problem is that my first method will contain a loop, and the second method needs to contain a break
:
def first_small(dct, second_method):
# Initial code
# ...
for i in dct:
# More code
# ...
for j in dct[i]:
second_method()
def second_small(j):
# Plenty of code
# ...
# ...
# and a break
if j == 'something':
break
# Inner code ended here.
second_small()
would raise a SyntaxError: 'break' outside loop
.
To fix it, I can replace break
in second_small()
with a custom exception and make first_small()
handle that exception, and break its loop when it finds it:
def first_small(dct, second_method):
# Initial code
# ...
for i in dct:
# More code
# ...
for j in dct[i]:
try:
second_method(j=j)
except MyException:
break
def second_small(j):
# Inner code
# ...
# ...
# and a break
if j == 'something':
raise MyException
# Inner code ended here.
However, I am not so sure this is the cleanest way to achieve that.
Question:
How should I split a method into two others, where first method will contain a loop and second has to break that loop?