I noticed the following pattern in socket.io-node:
// e.g. 1
socket.volatile.emit('bieber tweet', tweet);
// e.g. 2
socket.broadcast.json.send({ a: 'message' });
more generally, it seems to be of the style:
someObject.functionFlagA.functionFlagB.functionFlagEtc.someFunction(/* etc */);
What is this pattern called, where you add flags which may affect the execution of a function, in a chain of accessors which each return the target function (with any other available/appropriate chainable accessors)? When is it appropriate over, say, just passing some parameters to a function?
Looking at it gave me the idea of creating a sync object for my HTML5 web app like so:
// Saves someObj to localStorage AND to server-maintained session
sync.toLocalStorage.toServer.save(someObj);
…since it would be more self-documenting than:
// Saves someObj to localStorage AND to server-maintained session
sync.save(someObj, true, false, true);
Is this an appropriate use of above pattern?
EDIT 2011-12-06 13:06:15
For the curious, this is how socket.io implements it:
Socket.prototype.__defineGetter__('volatile', function () {
this.flags.volatile = true;
return this;
});
Which is used in chain to ultimately call the following internal function which sends a packet and clears the flags:
Socket.prototype.packet = function (packet) {
/* snip */
this.setFlags(); // clears this.flags
return this;
};
I would call it an example of a fluent interface.
From the Wikipedia article:
Of course in your example you have properties instead of methods. But looking at the socket.io-node code, the ‘properties’ are programmed as
__defineGetter__so you might as well say they are methods.With regards to your sync object for HTML5: think about the state of the sync object after calling save. Is it reset to its original state or does it remember the configuration? What happens if you call save twice in a row?
If it’s just about readability, you can also have callers pass in the configuration like so: