What is the cleanest way to use anonymous functions?
I've started to use Javascript a lot more, and as a r开发者_如何转开发esult I am writing things complex enough that organization is becoming a concern. However, this question applies to any language that allows you to nest functions. Essentially, when should you use an anonymous function over a named global or inner function?
At first I thought it was the coolest feature ever, but I think I am going overboard. Here's an example I wrote recently, ommiting all the variable delcarations and conditionals so that you can see the structure.
function printStream() {
return fold(function (elem, acc) {
...
var comments = (function () {
return fold(function (comment, out) {
...
return out + ...;
}, '', elem.comments);
return acc + ... + comments;
}, '', data.stream);
}
I realized though (I think) there's some kind of beauty in being so compact, it is probably isn't a good idea to do this in the same way you wouldn't want a ton of code in a double for loop.
Like any tool, it depends. You shouldn't always use it nor should you never use it. You should use it where appropriate.
You should use them where it's a simple 2 or 3-liner and there is no application for using it anywhere else.
You should use it in JavaScript where you gain a closure to isolate variables in the deal.
Above all, as long as another developer can look at the code and "get it", it's just fine. When I look at the code sample above, I do not "get it."
I think it depends on your aim and your application. You have to think about reusability and maintainability of code.
If you will never ever want to use an anonymous function again - use it as you are used to, but if you want tu reuse your code make it a global function.
Maintainability is easier to provide if your function calls are not anonymous.
Debugging is sometimes easier as well (error message: error in function {} does not help much).
How clean your anonymous functions can be depends on what they're doing and how long they are.
What I tend to do is only have simple anonymous functions as much as possible and just call out to externally defined functions (defined outside the code block or in another file...) when the function to call is long/complex instead of inlining it into the anonymous function.
This would make the code more legible/readable in the case that the functions are long. Also becomes more usefull if functions are used in more than one place - else the function would just be duplicated wherever it's used
精彩评论