Skip to content

Comment on Closures for class/module privacy considered harmful

Comments

Meh. The testing issue is easy to handle.

Just create a second entry point that exports everything you might want to test. "Secure it" (there is no real security here) to be only callable if a read-only global flag was set when the object was created.

In your private unit tests you set that flag, create the object, and get access to privates. In your normal code, there is no way to access those functions.

Yes, it is a hack. But I firmly believe that it is acceptable to have hacks to enable unit testing.

Whether or not any type of privacy enforcement is a good idea is a debate that I leave to others.

Or another way without the global:

    function myModuleReally() {
        return [useMe, testMe];
    }
    function myModule() { return myModuleReally()[0]; }
It'd be nice if the programming environment gave us a "can opener" (not globally available) to open up closures we've made -- like http://gbracha.blogspot.com/2012/07/seeking-closure-in-mirro... -- but we can do plenty without it.
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.