Question

I decided I needed something to help me a bit while implementing interfaces. So I added this function to the base.js file in the closure library.

/**
 * Throws an error if the contructor does not implement all the methods from 
 * the interface constructor.
 *
 * @param {Function} ctor Child class.
 * @param {Function} interfaceCtor class.
 */
goog.implements = function (ctor, interfaceCtor) {
    if (! (ctor && interfaceCtor))
    throw "Constructor not supplied, are you missing a require?";
    window.setTimeout(function(){
        // Wait until current code block has executed, this is so 
        // we can declare implements under the constructor, for readability,
        // before the methods have been declared.
        for (var method in interfaceCtor.prototype) {
            if (interfaceCtor.prototype.hasOwnProperty(method)
                && ctor.prototype[method] == undefined) {
                throw "Constructor does not implement interface";
            }
        }
    }, 4);
};

Now this function will throw an error if I declare that my class implements a interface but doesn't implement all the interface's methods. This has absolutely no gain from the end user's perspective, it is simply a nice addition to help the developer. Consequently how do I tell the closure compiler to ignore the below line when it sees it?

goog.implements(myClass, fooInterface);

Is is possible?

Was it helpful?

Solution

It depends on what you mean by ignore. Do you want it to compile down to nothing so that it only works in uncompiled code? If so, you can use one of the standard @define values:

goog.implements = function (ctor, interfaceCtor) {
  if (!COMPILED) {
    ...
  }
};

or alternately, only when goog.DEBUG is enabled:

goog.implements = function (ctor, interfaceCtor) {
  if (goog.DEBUG) {
    ...
  }
};

if these don't fit you can define your own.

Or do you mean something else entirely?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top