Anonymous Functions vs Named Functions for Node.js

I am a fan of anonymous functions, it just makes like easier and I find the syntax of passing functions around more expressive. Only problem I have found though is that when you have a bug, anonymous functions can give you a bit of a headache when tracking down what went wrong.


In the first example createServer is passed an anonymous function that gets called back. If something goes wrong you the error message is something like:

C:\Node\imageshare\server.js:14
        route(pathName);
        ^
TypeError: undefined is not a function
    at Server. (C:\Node\imageshare\server.js:14:9)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1610:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:91:29)

    at Socket.ondata (http.js:1506:22)
    at TCP.onread (net.js:374:27)
Which although is easy enough to track down in this example, you can see that the name of the function is not listed because it doesn't have one... Server.. As the project and file is tiny, it's not the end of the world. However in a world of call backs with anonymous methods I wonder if this would begin to get very tricky in a complex example. 
In the 2nd example, the function that's passed into createServer is named. When the same error happens the name of the function is given....
C:\Node\imageshare\server.js:13
        route(pathname);
              ^
ReferenceError: pathname is not defined
    at Server.process (C:\Node\imageshare\server.js:13:15)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1610:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:91:29)

    at Socket.ondata (http.js:1506:22)
    at TCP.onread (net.js:374:27)

I wonder if this would make for a much easier life in the long run?

Comments

Popular posts from this blog

Follow on from home automation post

Functional Filtering in Javascript

Derbyshire Dot Net Talk - Writing Robust Systems