Skip to content

Instantly share code, notes, and snippets.

@jaz303
Last active December 21, 2015 19:19
Show Gist options
  • Save jaz303/6353063 to your computer and use it in GitHub Desktop.
Save jaz303/6353063 to your computer and use it in GitHub Desktop.
//
// Pattern 1
// Single message handler function
// Pros: task can implement message handling however it likes
// Cons: makes it harder to reason about what messages an object understands
// A possible default implementation
object.send = function(message) {
if (typeof this[message.type] === 'function') {
this[message.type](message);
} else if (typeof this.anyMessage === 'function') {
this.anyMessage(message);
}
}
// But this would also be acceptable (transparent proxy)
// etc, etc
object.send = function(message) {
otherObject.send(message);
}
//
// Pattern 2
// Externalisation of pattern 1's "default implementation"
// Pros: message handling is system defined so very easy to reason about.
// because object layout is fixed, easy to send messages statically,
// as a normal function call... e.g. object.foo()
// Cons: loss of flexibility
// send is system-level function
function send(object, message) {
if (typeof object[message.type] === 'function') {
object[message.type](message);
} else if (typeof object.anyMessage === 'function') {
object.anyMessage(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment