Hacker News new | past | comments | ask | show | jobs | submit login

If your function is only called once it's better to leave it indented than to create a function.



Depends on the context/language I think. Splitting a block of code into a function gives it a greppable name that (ideally) succinctly describes the point of the block. You can have that block just headed by a comment inline to try and do the same thing, but comments are extremely prone to getting ignored and left to grow outdated when the purpose of the code around them changes. It's easier for the reader to just mentally abstract away that block if it's separated into a function. And if that block is worth testing, it's much easier to do when it's isolated into its own function.

There's reasons to keep the block inline too--like if you're working in a more resource constrained environment, or if the block isn't really isolated/self-contained enough to cleanly abstract away, or if the block in question isn't really doing anything substantial. But I wouldn't say that you should only abstract away code into functions to save yourself from literally copy/pasting the lines in multiple places.


You could argue that it's better to make the function; the compiler will probably inline it if it's only used once, and it helps avoid having the logic duplicated if it's needed again (or by lazy copy/paste programmers).


My point is not performance but that a function used only once is likely just contributing to one conceptual block of code. But now it's artificially divided up and one has to jump around to understand that code as a whole. There are exceptions of course but blindly adding functions to avoid indenting is probably going to lead to a harder to follow solution.


in js you can just leave the named function inline. i sometimes create functions that call themself so that i can just move it out if the code needs to be repeated, and i dont have to clutter the scope with more variables. with es6 js got bracket scoping, but i still prefer function scope and closures.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: