This site uses 3rd-party cookies for targeted advertising. If you do not agree to this, then please leave this site now. Otherwise please click on "Ok" to continue.
Ok
 
 

Don't Repeat Yourself

08-Jan-2015

While writing yesterday's blogpost, I noticed that I have several places where I load templates for blogposts, index-pages, RSS-feeds, whatever.

And I also noticed that each time the code is several lines long and that a lot of it gets repeated every time.

Let's take a look at one example:

var template = tools.loadFile(
    path.join( config[hostname].templatesDirectory, 'blogpost.html' ),
    'Unable to load template "blogpost.html"'
);

Wouldn't it be much better to replace the above code with this?

var template = te.loadTemplate( hostname, 'blogpost' );

Yes, looks much nicer. Let's do this. We'll start by adding the necessary code to template-engine.js.

exports.loadTemplate = function( hostname, template ) {
    return tools.loadFile(
	path.join( config[hostname].templatesDirectory, template ),
	'Unable to load template "' + template + '"'
    );
}

Good. We also need to add the require() statements for path and config to template-engine.js of course.

All that's left to do, is to go check the code for all the places where we load templates, and replace the old, long code with our brand-new single-line statement.

And that is all for today. Not only did the code get smaller and better, but also this blogpost turned out to be very small compared to yesterday's looooong article... :)

If you want to take a look at the full source-code as it was at the end of this blogpost, you can get it from GitHub:

git clone https://github.com/MichaelSchoebel/blogforum
cd blogforum
git checkout blog-2015-01-08

See you soon...

Comments:

Author: (Unknown)
2015-01-15 11:36 UTC
 

I find it quite telling how often we run into this. DRY is certainly a key principle in software development. In web dev, we still deal with terribly WET files [1]. Perhaps our fields are “too inviting” so to fix this sort of negligence by proper education…

[1] http://meiert.com/en/blog/20141009/css-dry-and-optimization/

You want to comment on this blog-post? If yes, then simply enter your comment in the field below and click on "Submit".

Comments are moderated at the moment thanks to some $%&# who thought it would be funny to post total nonsense here.

 


Back to the Homepage

A Programmer's Diary