| re: cutting down on callback nesting / spaghetti code. It can be hard to avoid; and having the community put together a PEP-8 style "best practices" to avoid
creating nested code is one of my fondest dreams. That said, I've written my fair share of [spaghetti code](https://github.com/chrisdickinson/tempisfugit/blob/master/li...) in Node,
mostly because JavaScript seems to lend itself to slapping together nested callbacks without slapping you on the wrist for writing unreadable code. In my experience, the best way to cut down on spaghetti code is to design your API around the [EventEmitter](http://nodejs.org/api/events.html#events.EventEmitter)
object. Consider this adaptation of the linked spaghetti code: https://gist.github.com/f8533ff57844b1e54558 Note that in the application code, there are no nested callbacks -- they're merely concerned with validating
the incoming data and passing the baton on to the next responder. Bonus points: the methods are in the order
of their ideal execution. Clients using the code can just do the following: var validator = new RepoPathValidator(path);
validator.on('data', function(repoData) {
// do whatever needs to be done with the repo.
});
// redirect all errors to console.error
validator.on('error', console.error.bind(console));
I'm very fond of using this method to destroy nested code -- I'm not sure how it's thought of in the community
at large, though (part of the reason I'm so eager for the community to put together the aforementioned PEP-8
style "best practices" guide!) |