Hacker News new | ask | show | jobs
by azeirah 3808 days 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 () {
            
            }
        }
    }

}
2 comments

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.
Ah 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.

A 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 :)