2

I have been trying to figure out the best way to write GAS libraries for a while now but I have a hart time figuring it out. I read Douglas Crockford's - Javascript: The good parts and I'm trying to implement these lessons in GAS. Every imported library adds global variable to your project (of the ScriptModule type), so the modular design pattern seems like a good place to start. Borrowing from the article I linked to such a pattern might look like this:

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

This module could then be called like this:

var module = LibName.MODULE;
var property = module.moduleProperty; // 1
var method = module.moduleMethod; // ...

From what I gather it is best have as few global variables as possible, so the general advice seems to be to save everything in one global variable. So the naming convention should then look something like this: LibName.PROJECT_NAME, where project name is the name of your single global variable which holds a module with everything else.

My goal here is to design secure, non-conflicting libraries. Am I right to use this design pattern? Has anyone developed their own robust design patterns for GAS libraries yet?

M. Oranje
  • 781
  • 5
  • 13

1 Answers1

3

When you import a script as a library in GAS a new "namespace" is already created for it, so there's no need or gain in creating another one yourself. You'd have have to "deference" it, like you did:

//there's no purpose for this
var module = LibName.MODULE;
var method = module.method;

//comparing if you write code directly on the library
var method1 = LibName.method1;

GAS is not client-side javascript, most of things you learn don't really apply to Apps Script, e.g. there's no DOM, no namespace conflict, no browser compatibility issues, etc.

By the way, I don't think this object nesting structure even works on Apps Script libraries.

Henrique G. Abreu
  • 17,406
  • 3
  • 56
  • 65
  • I think you are right about conflicting, the name of the library is also the namespace in which everything is saved. – M. Oranje Nov 27 '12 at 18:19
  • (sorry crossed the 5 min editing limit) I tested the modular pattern and is works as expected. In this design pattern you get to have an object with private variables and private methods that can only be accessed by the object itself. Are there better ways to handle objects in apps script? – M. Oranje Nov 27 '12 at 18:31
  • 1
    I don't think there is. But AFAIK variables/properties on the Library Script are never visible to the script which is importing it. And to hide methods, you can just append an underscore "_". Again, I don't think there's any gain in object-nesting an entire script just to use it as a library. – Henrique G. Abreu Nov 28 '12 at 02:07