
Ask HN: What are your thoughts on very long functions? - andrewstuart
I have a function that is very long - several hundred lines.<p>And I feel like I should break it up into smaller functions.<p>But the thing is, it&#x27;s <i>meant</i> to be several hundred lines of sequential instructions.  There&#x27;s just a long sequence of things that need to happen at this point in my application.<p>Breaking it into functions would seem to be introducing unneeded complexity. After all - functions are there to be reused.  And whenever you see a function you have to consider what places in the code might be using it.  Whereas in this case, if I broke this code into functions, none of those functions would be re-used.... they would all be called in sequence.<p>Admittedly it is hard to navigate up and down this long function which does have logical sections to it.  Maybe I should just bite the bullet and pull out each section into a separate function?<p>I dunno.  It feels wrong to have a several hundred line function but it also seems wrong to break it up, thereby increasing complexity.<p>What do you think?
======
iamkp
Any code that you write now will need to be edited in future for enhancement
or bug fixes. If you are able to split individual steps or sub tasks of the
main function into smaller sub functions, you would not be required to scan
through the entire code in future for any modifications. If the functions are
named properly, you can directly go to the function and edit it as required.

Also, assume that this big function breaks for some reason. Having sub
functions will make it easier for you or anyone else maintaining the code to
isolate it and track the source error in a much easier way.

So for me, functions are not just about re-usability, but also about
maintenance and readability of code.

------
viraptor
I'm not going to say you definitely need to split them, but there's a good
reason to do that, even if there are no other users - this read easier:

    
    
        def function:
          do_foo()
          something = do_bar()
          frobnicate(something)
    

than this:

    
    
        def function:
          // do foo
          lots
          of
          detailed
          code
          // do bar
          lots
          something = of
          other
          stuff
          // frobnicate
          ...
    

At least it makes the dependencies and logical blocks of functionality more
clear.

------
ggm
How well can you introspect about code logic across a scroll? Or a page? If
it's one unit of code, how can you mentally commit to it, without seeing all
of it?

The smaller thing: it's about how you interact with it in an editor, ide.

------
foldr
John Carmack agrees with you:

[http://number-
none.com/blow/john_carmack_on_inlined_code.htm...](http://number-
none.com/blow/john_carmack_on_inlined_code.html)

