Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Writing testable private methods with Node.js m...

Avatar for qubyte qubyte
June 19, 2014

Writing testable private methods with Node.js modules

In this 5 minute lightning talk, I present a way to write private methods that are still trivially testable with Node.js modules.

Avatar for qubyte

qubyte

June 19, 2014
Tweet

More Decks by qubyte

Other Decks in Programming

Transcript

  1. Why test? • Assert behaviour. Publish with confidence. • Maintain

    behaviour. Refactor with confidence. • Add tests after bugfixes. Avoid regressions.
  2. Why use private methods? • Small API surface. Less for

    users to learn. • Protect internal implementation to allow refactoring.
  3. Modules help us out! function AsyncAttendee(name) { this.name = name;

    } // Make the module a reference to the constructor. module.exports = AsyncAttendee; // "private" methods take context as the zeroth argument. function sayHello(asyncAttendee) { return 'Hello ' + asyncAttendee.name + '!'; } AsyncAttendee.prototype.hello = function () { console.log(sayHello(this)); };
  4. Option 1 function AsyncAttendee(name) { this.name = name; } //

    Make the module a reference to the constructor. module.exports = AsyncAttendee; // "private" methods are prefixed with _ . AsyncAttendee.prototype._sayHello = function () { return 'Hello ' + this.name + '!'; }; AsyncAttendee.prototype.hello = function () { console.log(this.sayHello()); };
  5. Option 3 // index.js var privateMethods = require('./private'); function AsyncAttendee(name)

    { this.name = name; } module.exports = AsyncAttendee; AsyncAttendee.prototype.hello = function () { console.log(privateMethods.sayHello(this)); }; // private.js exports.sayHello = function (asyncAttendee) { return 'Hello ' + asyncAttendee.name + '!'; };
  6. Option 3 Use a namespace module. • "Public" to the

    filesystem (and therefore tests). • "Private" to JS outside your module.