In the first post of this series we looked at how Interfaces work, and if NodeJs could/should have them.
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.
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:
- Methods exist on the service without any checking needed.
- When you require the service your domain level code doesn’t need to know what concretion is being used.
- 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%:
- The boilerplate needs to be added to app scaffolding
- 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.