Explicit over clever
Posted on December 19, 2015 • 2 minutes • 221 words
I always prefer explicit over clever, hacky hack. Explicit make the code looks clearer, more maintainable and leaning toward a more predictable behavior (aka junior developers will be less likely to mess it up).
Take an example of this code where I have a folder called providers
. This here below is the content of the index.js
file which basically read all the files in that folder (except index.js
), require them and then module.exports
that. It seems simple enough right?
var fs = require('fs');
var path = require('path');
var basename = path.basename(module.filename);
var providers = {};
var extension = '.js';
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === extension);
})
.forEach(function(file) {
var provider = require(path.join(__dirname, file));
var key = makeKey(file,extension)
providers[key] = provider;
});
/* ... */
Now, take a look at this code where I explicitly require all the files in that folder (sounds exhausting right?)
let providers = {
Auth: require('./auth'),
User: require('./user'),
Health: require('./health')
}
/* ... */
module.exports = providers
Now, say if you were a newly joined member of the project, which looks less intimidating to you? I’m not saying we can’t achieve both explicit and clever at the same time; but if I need to make a choice selecting one over another, I would always go with explicit.