On Sun, Jul 01, 2012 at 04:04:12PM -0700, Alexey Petrushin wrote:
> There are some good use cases for control flow libraries, but, sadly,
> in most cases the end result is even worse than without it.
>
> It seems there's no good solution to this problem - code looks ugly no
> matter what You do - with or without control flow libraries.
>
> So, I believe currently the "fuck that" approach is the best option.
> Just write ugly waterfall code and don't care about it very much ;)
I've come to depend on two helper functions...
function validator (callback) {
return function (forward) { return check(callback, forward) }
}
var __slice = [].slice;
function check (callback, forward) {
return function (error) {
if (error) {
callback(error);
} else {
try {
forward.apply(null, __slice.call(arguments, 1));
} catch (error) {
callback(error);
}
}
}
}
When I start a function I create a check function like so...
var check = validator(callback);
... or else if I only call it once, I use `check(callback, func)`.
Then I use hoisted functions to name the steps in my procedure. This is
more verbose than a control flow library, but it is pretty easy for to
read and therefore maintain. Calling hoisted functions by name prevents
the formation of a template of doom.
The `check` function saves the trouble checking errors, which saves an
if/else block and therefore saves a layer of doom.
It's verbose, but I don't feel that it's ugly.
var fs = require('fs');
function deltree (directory, callback) {
var files, count = 0, check = validator(callback);
fs.readdir(directory, extant);
function extant (error, $1) {
if (error) {
if (error.code != 'ENOENT') callback(error);
else callback();
} else {
list($1);
}
}
function list ($1) {
(files = $1).forEach(function (file) {
stat(path.resolve(directory, file));
});
deleted();
}
function stat (file) {
var stat;
fs.stat(file, check(inspect));
function inspect ($1) {
if ((stat = $1).isDirectory()) deltree(file, check(unlink));
else unlink();
}
function unlink () {
if (stat.isDirectory()) fs.rmdir(file, check(deleted));
else fs.unlink(file, check(deleted));
}
}
function deleted () {
if (++count > files.length) fs.rmdir(directory, callback);
}
}
With a control flow library, I find that code gets cryptic when it gets
complicated; precisely the time it is best to be clear. The real work is
being done behind a curtain. I miss the names when they aren't there.
This is complexity I want to see.
--
Alan Gutierrez - http://twitter.com/bigeasy - http://github.com/bigeasy
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en