Ask HN: What are your thoughts on very long functions?
5 comments
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.
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.
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.[deleted]
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.
The smaller thing: it's about how you interact with it in an editor, ide.
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.htm...
And I feel like I should break it up into smaller functions.
But the thing is, it's meant to be several hundred lines of sequential instructions. There's just a long sequence of things that need to happen at this point in my application.
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.
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?
I dunno. It feels wrong to have a several hundred line function but it also seems wrong to break it up, thereby increasing complexity.
What do you think?