Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of declaring variables without assignment?

Tags:

javascript

I'm studying some CreateJS samples and in one of them I've seen this and I'm wondering what use it's for

(function() {
    var c = createjs;
    var a = function(blabla) {
        this.blabla = blabla;

    var p = Game.prototype;
    p.a;
    p.b;
    p.c;
    p.d;
    /*
    ... 15 variables like that ...
    */
    p.init = function(param) {
        /* blabla */
    }
    /*
    ...
    long code after that
    ...
    */
})();

It's on the github samples, in the /createjs/sandbox-master/PlanetaryGary directory, it's the file js/Game.js

like image 268
Olivier Pons Avatar asked Dec 14 '22 20:12

Olivier Pons


1 Answers

I'm the original author of the code in question. This pattern comes down to the simple philosophy that good code is self-documenting.

It's worth a quick mention for those coming into this blind that those properties are not actually named a,b,c, etc. It's also worth mentioning that they are usually assigned a default value (though not in this particular case).

The up-front variable declarations explicitly define the fields that will be associated with the "class". This allows a developer to scan from the top down, and establish a mental model of the data the class operates on prior to looking at the methods that operate on it.

It provides a convenient, contextual place to hook doc comments, though the referenced code is not documented.

/**
 * Docs for firstName here.
 **/
p.firstName = "default";

/**
 * lastName docs.
 **/
p.lastName = "default";

Lastly, I've found it encourages a more thoughtful approach to data and documentation. The act of defining a new property becomes an opportunity to view the existing properties and evaluate the necessity of the new field. I've seen a lot of bugs and poor code result from devs appending properties to classes willy-nilly.

It's also a lot harder to forget to document new properties (and much easier to quickly spot undocumented properties) when you're explicitly defining them in a dedicated area of your code.

like image 86
gskinner Avatar answered Dec 17 '22 10:12

gskinner