Hacker News new | ask | show | jobs
by chatmasta 1126 days ago
Extracting to a function means you need to give it a name. There is a middleground where you might want a function for control-flow purposes, but giving it a name makes the code look more complicated than it needs to be. Personally I just use an IIFE in those situations - and I don't see much benefit from run() as compared to an IIFE.
2 comments

It already has a name, even in the contrived example OP named it "x".

The extracted function can simply be getX() or calcX() or generateX() - which verb chosen can tell the reader roughly the origin/complexity of X without having to read the function body: Does it already exist or are we creating it here? If we're creating it, is it internal or is it likely to require other resources like an API call?

In a more concrete example I'm sure it can get a better name than that, too.

That's true when you're assigning the result of the function to a variable, but what about the use case where you're replacing a ternary within JSX code? You could extract the evaluation to an assignment of a variable outside of the JSX, but that's the kind of unnecessary complexity that IMO is sometimes worth avoiding.
We are being quite abstract here since we are lacking real-life examples here, but using a variabe assignment intead of an inline if/else assertion does not add any complexity at all. It adds more code, yes. More complexity? No. Is it good or bad to add more code? I would answer: the more easily readable and maintainable version of the code is the better version of the code. More times than not, more code is the better version (when it is dry, with correct abstractions and good names).
If you're only consuming the variable once, and it's inside a declarative syntax like JSX, then I'd argue it's more readable to use an anonymous function, because the reader doesn't need to look elsewhere, and the function is defined in the same place where it's evaluated. And you don't need to bother thinking up a name for a variable, which could lead you to prematurely generalize.

Personally, most of the time I assign to a variable. But I do think there are cases where the IIFE is an appropriate and more elegant approach.

I do not see anything wrong with what you are describing, but in my experience, going into that excercise of extracting a function and giving it a name is an insightfull process. It gives you time to reason about what you are building instead of going full coding-monkey mode. Instead, you pause a bit and reflect. To this day I have never regreted doing that.