In the first post of this series we looked at how Interfaces work, and if NodeJs could/should have them.

Since then I’ve been doing some research which has led down all sorts of paths, like how the require function is effectively a service locator. How we could use the require function to bind concretions to interfaces, how in JavaScript duck typing is used in place of Interfaces. Plus all sorts of other related topics.

In this part I’m going to look at how we can in the context of an app get the benefits of Interfaces without actually having Interfaces, and it centres around service location, proxies and the module system.

The Example

As you can see there are no Interfaces, but we can have a consistent API directly powered by the app. Quite simply we define our app services and proxy the functionality down to other npm provided modules without exposing the concrete “module” in use.

This to me is a bit like both the service locator, and the factory pattern combined, on-top of the module pattern! But has the added benefit of providing Contracts (ala Interfaces) for our application to consume within the domain.

In terms of how this related to Interfaces you can be sure:

  1. Methods exist on the service without any checking needed.
  2. When you require the service your domain level code doesn’t need to know what concretion is being used.
  3. Swapping out the concretion is more maintainable (could still be improved, but does the job)

There are a few things I don’t think are 100%:

  1. The boilerplate needs to be added to app scaffolding
  2. Theres no consistency at the package level, meaning there is still a little refactoring needed if you swap out a concretion.

In the example I haven’t used the ES6 proxy feature just to illustrate the idea without confusing it with other features.

Is this a solution? Maybe for some apps, for the global NodeJs community? No I don’t think so, in larger apps you would a lot of the time just be replicating a packages methods either by inheritance or proxying.

In terms of the community even it was recommended, that’s all it would be, a recommended pattern, you the developer would have to implement it.

An interesting point I found when researching possible solutions is that implements, and interface are both strict type reserved words, so its possible this is already on the agenda for future JavaScript version.