Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js how to implement polymorphism?

I'm trying to implement an application using node.js and other related technologies. Heading from java land polymorphism but natural, but for the classical programmer node works differently.

The application will load new code during run-time provided by the user. In order for the main core to use this code "we" need to agree on some kind of a convention. Knowing how new Node is I wasn't that surprised that I didn't find the answer. The problem is this issue is rather vague in JS too.

Requirements:

  1. Strong decoupling.
  2. loading new code in run-time.
  3. The solution should be applicable so I can share as much code as possible with the browser.

Update:

  1. I did fiddle around with duck-typing, I've also encountered ideas from Clojure in regards to protocol based implementation.
  2. I would appreciate some code in the answer.
like image 332
qballer Avatar asked Aug 03 '12 14:08

qballer


1 Answers

JavaScript, just like most other scripting languages (i.e. no compile-time type checking) does polymorphism through duck typing.

If you're from Java-land you're probably looking for Dependency Injection which generally provides uber decoupling. You can probably use google to find a good dependency injection framework for Node, like this one.

Although truthfully you can probably just make a single Javascript/Coffeescript file that does all the wiring and config loading.

Because of the flexibility of Javascript just about every form polymorphism has been implemented (traits, interfaces, inheritance, prototypes). Each have their advantages/disadvantages but almost all are runtime check (if any) and not compile time.

Personally I would probably just use either Coffeescripts inheritance, traits.js or Javascript's builtin prototype chain.

EDIT: However since you're talking about allowing users to extend the system then callbacks and/or custom events are the preferred approach (i.e. higher order functional programming and event-bus). If you're looking for something substantial like a plugin system then loader-js looks rather complete (tip of the hat to @Larry Battle).

like image 116
Adam Gent Avatar answered Oct 24 '22 00:10

Adam Gent