A case against the module design pattern

by Jason on November 28, 2013

The module design pattern is a particularly popular design pattern used in JavaScript these days.

The main reasons for its use are:

  1. “Private” variables via closure
  2. Global imports

A simple example of a module design pattern implementation looks like this:

var MODULE = (function(args) {
var _private_variable = null;
var _private_method = function() {};

this.public_variable = null;
this.public_method = function() {};
}(GLOBAL_IMPORTS));

This is a very common pattern among JS devs but it is quite problematic.

The main issue is that it’s impossible to test any of the non-public methods. A common argument to this is that private methods shouldn’t be tested.

My argument against the module design pattern is this:

1. Your code is visible by anyone at any time. You’re not protecting anything. If you’re using JS to store sensitive information (encryption keys, for instance) then you’re out of your mind.
2. You limit the testability of your code
3. If you don’t follow a solid coding guideline then it could be difficult for new engineers to parse your code.

The module design pattern can be useful if private methods/variables are used sparingly and for the right reasons.

Image Preloading Optimization

by Jason on October 11, 2012

If you find yourself needing to load many images for your web application there are some things you must consider in order to achieve maximum performance.

WTF am I doing?!

Can you avoid so many images all together? Consider using CSS sprites.

Some other obvious considerations:

  • Compress the images
  • Use a CDN such as Amazon Cloudfront for hosting
  • Ensure proper caching is in place. Browser and server-side.

Duh!

Ok, so you’ve exhausted the obvious, and yet you still have a ton of images to preload. How can we optimize this?

The first thing that you should realize is there is a limit to the number of concurrent downloads a browser can perform per host.
For most modern browsers this number is 6, but occasionally it can be higher or lower (FYI this is not well documented).

You’ll notice that big sites like Google, Flickr, etc tend to utilize 2-5 CDN hostnames to host their assets. This is the number you should strive for if possible.

The downside to additional hostnames is the extra latency involved in performing DNS lookups, so adding extra hosts will not always result in faster downloads. You must test.

Once you get extra hosts in place, think about using this library to help properly optimize the download queues.

JavaScript Image Preloader

JavaScript Event Factory

by Jason on August 5, 2012

I have started a new project this weekend on Github that I’m calling the JavaScript Event Factory.

I am mostly doing this so I can understand how to build messaging systems in JavaScript and it’s also my attempt to understand the convoluted Event-based architectures.

Currently this project is very much experimental, but as it grows the idea is that it will encapsulate the most common messaging patterns under a single namespace and follow the proper design patterns.

JavaScript Event Factory currently supports:

I may expand this in the future to add more patterns, but currently these appear to be the most widely used.

The thing I like most about my solution, so far, is that it does not rely at all on any DOM Events. Perhaps it’s naivety, but I saw no real need to utilize DOM Events, except for the useful Event.stopPropogation and Event.preventDefault. However, I have implemented my own version of this for when it’s necessary.

This approach allows me to create a DOM-independent messaging system. So this would allow simple objects to communicate with other objects without having to be tied to a particular node.

As always, your feedback would be highly appreciated.

Github Link

JavaScript Patterns Textmate Bundle

by Jason on June 25, 2012

Last night I started a new project that I’ll be adding to over time.

It’s a Textmate Bundle that will create skeleton code for various popular JavaScript patterns such as Module, Singleton, and Sandbox.
More will be added soon and I hope others will contribute!

JavaScript Patterns Textmate Bundle

PackageStore

by Jason on June 10, 2012

Today I started a new project named PackageStore which I expect to be iterating on over the next few weeks.

The main purpose of this library is to provide an interface exactly like localStorage for setting/getting variables, but behind the scenes storing the data in a single localStorage key. Also, it should provide very simple hooks to encrypt/decrypt this data.

So, why do this?

Modern applications are beginning to move to JavaScript. With the advent of Backbone and various other systems there has been a movement to move the majority of application code to the browser instead of the server. Managing application state now becomes an instant concern for any competent JavaScript developer.

Given that JavaScript applications are inherently manipulatable (read: insecure) you have to think of ways to make JavaScript hackers job difficult. So you do some common things such as compiling JavaScript, minifying JavaScript, using the Module design pattern so “private” variables are not easily manipulated, etc.

Another obfuscation tool is to store all state management variables within a single key, and encrypt the contents.

I welcome your feedback on everything!
Github Source

Konami Code in JavaScript

by Jason on June 9, 2012

Others have already done this many times, but I thought it would be an interesting challenge this morning to implement the Konami code in such a way that you can attach a callback which will be fired only after the code is successfully entered.

This generic approach is nice because it allows developers to do whatever they want when the code is entered.

Check it out
Github

HTML Compressor, Closure Compiler, and Ant.

by Jason on June 6, 2012

The other day a friend of mine posted on Facebook that she was 10,000 days old.

About an hour later, I had created the Days Since Birth utility.

Still wanting to code more, I decided to make this project a bit more mature.

So, using Ant I was able to setup a simple target that compresses the HTML and runs the JavaScript through Google’s Closure Compiler.

I am considering other options, such as Linter’s (even though the code is already JSLint compatible), but would love other’s thoughts on it.

Source

Python Function Timer Decorator

by Jason on March 26, 2012

I find myself often timing how long code blocks take to execute so I’m able to discover bottlenecks and compare performance between iterations.

A quick & simple way to do this is with a handy Python decorator.

import time
import logging as log

def log_timing():
    '''Decorator generator that logs the time it takes a function to execute'''
    #Decorator generator
    def decorator(func_to_decorate):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func_to_decorate(*args, **kwargs)
            elapsed = (time.time() - start)
            
            log.debug("[TIMING]:%s - %s" % (func_to_decorate.__name__, elapsed))
            
            return result
        wrapper.__doc__ = func_to_decorate.__doc__
        wrapper.__name__ = func_to_decorate.__name__
        return wrapper
    return decorator

Automating Fixture Instantiation in Mocha using Async

by Jason on January 31, 2012

My latest Node.JS project has been entirely test-driven and I always strive to write very simple & concise tests. Convoluted code in a test will be far less likely to be maintained.

So when test driving my latest model, I found myself using hundreds of lines of code just to instantiate models using pre-built fixtures in the before function. Not ideal.

I much prefer this type of code:


var my_model_fixtures = require(app.root+'/spec/models/fixtures/my_model_fixtures.js');

describe('My Model', function() {  
  before(function(done) {    
    this.my_models = new Array;
    var that=this;
    
    async.map(['fixture1', 'fixture2'],
      function(my_fixture, iterator_callback) {
        var my_model = new MyModel(my_model_fixtures[my_fixture]);
        my_model.save(function(err,data){
          if(!err) {
            iterator_callback(null, my_model);
          } else {
            iterator_callback(data, null);
          }
        });
      },
      function(err,results){
        if(err) {
          console.log("Error instantiating fixtures: "+err);
        }
        done(err);
      });
  });  
});

Self Updating Solr Stopwords

by Jason on December 17, 2011

If you are looking to edge out a bit of performance from Solr one of the many things you can do is optimize your Solr Stopwords file. The more entries you have in this file, the less terms that end up in the Solr index.

Creating a Stopwords File

When developing a Stopwords file, it’s good to initially think about what terms you might want to ignore. A good starting point could be browsing the Stopwords community.

Self Updating Stopwords File

Once your system has been running for a while and you have a decent index you want to constantly examine the indexed content for data that shouldn’t be indexed.

A great way to do this is to use the TermsComponent. Using the TermsComponent, you can easily determine the top keywords (and the number of indexed documents it’s associated with) for a given field.

Example:
http://url.to.solr/solr/terms?terms.fl=MY_FIELD&terms.limit=1000

This will return the top indexed keywords (sorted by frequency descending). The example is returning the top 1000 indexed keywords for MY_FIELD.

Note: It is wise to perform this operation on a Tokenized field. Doing so on a non-tokenized field will simply result in the frequency of entire sentences (or more) occurring and not the frequency of keywords as you might expect.

Once you have this list in front of you comb through it and look at all of the keywords that are indexed which have absolutely no value to you. Immediately add these terms to your Stopwords file and ReIndex.

Some smart (but perhaps not wise) person could quite easily create a script to automatically perform a TermsComponent query, extract the top terms, and auto-update the Stopwords file. But, this would require some really tight controls so as not to nullify your entire index.