3 ms·
The first professor who I took a programming class from told us that anytime we needed to indent something we should be asking ourselves if we needed to create
by calafrax 9y ago
The first professor who I took a programming class from told us that anytime we needed to indent something we should be asking ourselves if we needed to create a new function and most times the answer would be yes.
It was good advice.
- wvenable 9y agoIf your function is only called once it's better to leave it indented than to create a function.
- mklim 9y agoDepends 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.
- ams6110 9y agoYou 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).
- wvenable 9y agoMy 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.
- z3t4 9y agoin 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.