|
|
|
|
|
by al2o3cr
3808 days ago
|
|
To expand on that, something I sometimes find useful with giant functions with too many 'ifs' is to pull out the code that runs for each of the possibilities. Frequently I'll discover that there are actually several different overlapping functions (possibly with some common parts) mashed together with the differences wrapped in 'if'. Ferinstance: def giant_method
if thingy1?
do_stuff
else
do_something_else
end
do_common_stuff
if thingy1?
finish_up_for_thingy1
else
finish_up
end
end
It's easy to spot that there are really two paths through the method (depending on what thingy1? returns) in this simplified form, but rewriting it will make it clearer even in a 2k line function: def giant_method
if thingy1?
do_stuff
do_common_stuff
finish_up_for_thingy1
else
do_something_else
do_common_stuff
finish_up
end
end
This is also useful even when the 'if' clauses aren't identical - even then, there are frequently implied relationships (for instance, if one checks if something is positive and the other checks for zero) that can simplify things. |
|