Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
themeEclipse
languagejavascript
linenumberstrue
function oldApproach(x,y,range) {
  // do stuff the hard way
}
function newApproach(x,y,range) {
  // use enumRange()
}

But there's two problems with that approach:

  1. Both functions are available regardless of API version – it's quite easy to use the wrong one.
  2. To avoid using the wrong one, you need to work out which function to use every single time – that's crufty and slow
  3. If, at a later date, an new API feature provides an even better way to do things (superAwesomeLatestApproach) you'd have to go and update all places in your code that check what function to use

To get round this problem, we can define the two functions in a closure and have the closure output the right function depending on whether the enumRange() function is available or not:

...

  1. It's no longer possible to use the wrong function because nothing outside getThreatsNear() can access the oldApproach() or newApproach() functions
  2. The rest of your code doesn't need to worry about which function to use (it's handled by the "if .. else" statement in getThreatsNear()
  3. If superAwesomeNewerApproach becomes available, we can deal with it in one single location - although it will make the "if ... else" statement more crufty

But even this approach is still somewhat inefficient. Every time you call getThreatsNear() it has to do that if statement. While it's not a lot of processing, it still seems wasteful to have to do that typeof check every single time the function is called. If you have lots of places doing that sort of thing, and you run that code over and over again, it all starts to add up to cause performance problems.

We can solve that problem like this:

Code Block
themeEclipse
languagejavascript
linenumberstrue
var getThreatsNear = (function(){
 
  var oldApproach = function(x,y,range) {
    // do stuff the hard way
  }
  var newApproach = function(x,y,range) {
    // use enumRange()
  }
  // note we're returning a function, not running it (no "()" on the end)...
  if (typeof enumRange != "undefined") {
    return newApproach;
  } else {
    return oldApproach;
  }
 
})(); // <-- "()" here means we're running the anonymous function
 
// then in your code use this:
var threats = getThreatsNear(someX,someY,someRange);

...