SMIRF 2.0

Late last year, I told you about the SMIRF JS pattern I’ve been working on. Since then, I’ve had quite a lot of opportunity to use it in the field and refine it.

The biggest weakness with the old SMIRF pattern was the need to pass the instance variables around all the time. It meant there was a tiny memory leak in the api, since wrapper functions needed to add the iVars argument to all calls.

What I’ve changed is that iVars is now accessed via a method getIVars┬áin the “constructor”. There’s a localised randomly generated private key which must be passed in to get the instance variables. That way, nothing outside could grab them and clobber them (unless you write a method to deliver them, obviously!

So, here’s the updated pattern:

var employeeFactory = (function(){
  var PRIVATE_KEY = String(Math.random()), giveRaise, fire;
  
  giveRaise = function(percent){
    var iVars = this.getIVars(PRIVATE_KEY);
    percent = percent || 0;
    console.log(iVars.salary);
    iVars.salary = iVars.salary * (1 + (percent/100));
    return iVars.salary;
  };
  fire = function(){
    var iVars = this.getIVars(PRIVATE_KEY);
    //long, drawn out legal process that takes 5000 lines
    iVars.currentlyEmployed = false;
  };
  
  return function(name, salary){
    //This is essentially a constructor function
    var iVars = {
      //Instance variables. All state info should be stored here
      name: name,
      salary: salary,
      currentlyEmployed: true
    };
    return {
      getIVars: function(key){
        if (key === PRIVATE_KEY) {
          return iVars;
        }
      },
      giveRaise: giveRaise,
      fire: fire
    };
  };
}());
var employee1 = employeeFactory('Bob', 30000);
var employee2 = employeeFactory('Mary', 21000);