What are Interfaces?
I’m no expert, but interfaces allow you to rely on methods existing, and returning expected values from any concrete implementation. Reading any OOP Design Principles book will tell you:
Programme to an Interface, not an implementation.
I don’t know who originally coined the phrase, if anyone does please let me know and I can attribute accordingly.
In PHP this is pretty simple:
A term used recently within the Laravel Community is to treat Interfaces like Contracts (in fact the framework Interfaces are name spaced as Contracts). Your Interface dictates whats available for use, and your implementation must adhere to it.
My knowledge of Interfaces beyond PHP is very low, but I think PHP has a really good thing going with the introduction of PSR by PHP-FIG. If you don’t know PSR is effectively a community driven standard set of interfaces for use across any PHP application.
The benefits I see from Interfaces are as follows.
Say your working on an app and you need a logger class to log any issues encountered. So you search your chosen languages package management system, find a decent logger package and start using it.
All is going well until you realise the logger you chose is being abandoned, or you find out there is a better performing logger package.
Ok so now you need to run through your app and replace all uses of the old logger with the newer package. Not great for maintainability, and this is just a logger class! If you’re doing this for every aspect of the application it will lead to lost development time maintaining compatibility for your chosen packages.
Whereas if for example your app was in PHP and you programmed to
Psr\Log\LoggerInterface (using a container of some sort).
When you wanted to use a different logger, you simply replace the concrete implementation of the
LoggerInterface within your container. As you are using the interface you know for sure your app uses only the prescribed API to the implementation. This wont break when you swap out the implementation.
This scenario only gets worse the larger your app gets. Programming to an Interface is more maintainable, and concise as your coding to the prescribed API.
Does NodeJs have an alternative?
While researching I did find some comments suggesting a few drawbacks, one being performance which should be noted, as in reality any implementation will be a runtime task which will have some overhead, but the size of this I suspect would be negligible, 1 or 2 function calls isn’t going to break the web, but its a valid point and should be weighted against the benefits.
All in all I think Interfaces of some sort would work, and work well within NodeJs, how they look I don’t know, but its something I will be exploring.
No other programming language with Interfaces (that I know of) utilises module based design, so the traditional Interface may need to altered in some to work with module driven development.