5 ms·
Something I found to be really useful is to remove all statements inside the code, so you'll be left with large skeleton structures. Look at it from a distance,
by azeirah 11y ago
Something I found to be really useful is to remove all statements inside the code, so you'll be left with large skeleton structures. Look at it from a distance, (small font), see some patterns. Can you split it up?
getting a feel for the structure of the function helps me understand it.
Ex:
function someFunction () {
if () {
for () {
if () {
} else {
}
}
if () {
for () {
}
}
}
}
- pinkunicorn 11y agoAh I do this with if() block folding in Vim. In this case, the developer actually has return statements inside some if blocks. A general point that has stood out from all comments is to first understand how the function achieves what the function is trying to achieve.
- odonnellryan 11y agoA return point inside an if statement is a great place to do a refactor. Refactor anything inside that if into its own function, write a test, and see what happens :)
- al2o3cr 11y agoTo 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.