Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That last part's gonna need a citation. I've never experienced a difference myself. Once methods get big, assuming no usage of IDE functions (regions), going through these large code sequences will quickly fill my mental space, whereas stashing away the code in methods does not.

On the flip side, smaller methods do not encourage code duplication and help set up unit testing for those who desire it. There are also arguments to be made depending on language and coding style (e.g. encouraging guarding, early returns and avoiding bracket use and indentation in old imperative-style Java).



The only citation can be experience, especially since it's so heavily dependent on the specifics of the situation.

If the refactored mini-function captures something very discrete, like popping an item off of a queue, then of course it's a big win. You'll often ask yourself what the hell the original developer was thinking spilling all these details into an unrelated context.

But if that chunk of code only really makes sense in the context of that function, then moving it into a separate function might not do anything except force future readers to flick back and forth between between the various helper functions and the top-level coordinating function. Have you honestly never had that experience? If so, maybe you're lucky enough to have never worked on a code base containing that mistake.

The only true rule is never to blindly follow rules! Feel free to bear good practices in mind, but always make a new, independent assessment for each situation where you might apply it. For the rule about refactoring into smaller functions, think about whether future readers are indeed going to be able to (confidently) avoid looking at the implementation of those smaller functions, because their meaning is so clear from their signature, or if you're just adding extra navigation and mental work. Sometimes it will go one way, maybe even mostly it will go that way, but sometimes not.


The last paragraph ended up more preachy and patronising than I meant. All I meant was, I've certainly come across code from devs that followed rules too blindly.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: