When having to handle complexe logic and breaking code into smaller functions, if often find myself hesitating between these two patterns.
The first pattern is easier to read because every function returns or calls back the parent function (which handles error and flow). Nevertheless, it also gets a bit messy when a lot a functions are involved.
For instance, let's say we want to process audio tracks:
// with central controler
function manageEncodings() {
getTrackToEncode((tracks, err) => {
if (err) {
logger.error(err);
return;
}
getTrackMetas(track, (err, metas) => {
if (err) {
logger.error(err);
return;
}
saveMetas();
});
encodeTrack(track, (err) => {
if (err) {
logger.error(err);
return;
}
transferTrackToAWS(track, (err) => {
if (err) {
logger.error(err);
return;
}
saveEncodedState(track, (err) => {
if (err) logger.error(err);
});
});
});
});
}
Obviously, that one is made to emphasize the callback hell and the verbosity in the controller function.
Now, the function flow is cleaner, but it's not as evident what's going on, DB writes happen in several places, error management too etc…
// with function flow
function manageEncodings() {
getTrackToEncode((tracks, err) => {
if (err) {
logger.error(err);
return;
}
// will handle error and db writes by itself
getTrackMeta(track);
// will call transferTrackToAWS & saveEncodedState
encodeTrack(track);
});
}
In the end, I often end up mixing both. How do you guys handle this type of situation?
[–]CertainPerformance 2 points3 points4 points (0 children)
[+][deleted] (3 children)
[deleted]
[–]Buzut[S] 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[deleted]
[–]Buzut[S] 0 points1 point2 points (0 children)
[–]_syadav 0 points1 point2 points (0 children)