You should probably put that in a function…

By David Pratt / Tags: , / No Comments / Published: 14-09-09

I’ve worked on a lot of sites in my time, most of which have comprised of a large body of code that has been developed over a period of years. What seems to be a common theme to me is the difference between the sometimes lack of craftsmanship in the JavaScript code compared to the back-end languages. I’m sure there are many reasons for this, but I think that it is largely due to the fact that the need for good front-end engineering has only been widely recognised since the web standards movement really began to take hold a few years ago. Prior to this when JavaScript was unfashionable, I’m sure that the majority of the brightest graduates leaving university were swayed towards the more serious languages (.Net, Java etc.) because that was where the money was, leaving the door open just enough for the copy and paste brigade to gain a foothold.

Anyway, I intend this post to be the first in a series of posts about where some JavaScripters go wrong with the basics.

So, pet hate number 1 is… When the same line or sequence of code is repeated in a number of locations across a file. Here’s what I mean:

//Calculate grade
grade = (userTotal / maxPossible) * 100;
grade = Math.round(grade);

Fairly simple I’m sure you’ll agree – the code is calculating some sort of grade and then rounding it off. Nothing wrong with this in itself, but we can make it cleaner by abstracting it into a function:

function calculateGrade(userTotal){
    grade = (userTotal / maxPossible) * 100;
    grade = Math.round(grade);
    return grade;
}

You could even do it on one line if you really wanted too:

function calculateGrade(userTotal){
    return Math.round((userTotal / maxPossible) * 100);
}

The original line of code can now be replaced with something a lot more readable:

grade = calculateGrade(userTotal);

If this were just in one place in your code then fine, no massive benefit has been gained bar a bit of readability, but if this same calculation is carried out in multiple places, then the benefits really begin to emerge:

  • If the grade calculation changes, then it only needs to be amended in one place.
  • It avoids duplicate code, and uses less of it.
  • Improves performance.
  • Reduces complexity, and also isolates it.
  • The program becomes a little more self-documenting.
  • Enables code re-use.

If I sat down and thought about it, I’m sure I could reel off many more reasons, but even for just these few it has got to be worth investing the time to understand the basics of functions and abstraction.

Category: Tech

Tags: ,

Posted: on September 14th, 2009 at 12:25 pm.

Feeds: RSS 2.0

Leave a reply