Milen Kovachev
Milen Kovachev

Reputation: 5371

Program against an interface in node.js?

Dependency injection and programming against an interface is standard in C# and Java. I am wondering can this be achieved in Node.js too? For example I am programming a memory cache module and ideally it should expose an interface, let's say with two methods getKey and putKey. I can have one implementation with ioredis and another one with just plain memory cache. But my application will only depend on the memory cache interface.

Upvotes: 1

Views: 264

Answers (1)

Fábio Junqueira
Fábio Junqueira

Reputation: 2781

Javascript uses Duck Typing

In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

from Wikipedia - Duck typing

This means that you can make a function expect a object as an argument and assume it has some specific functions or properties. i.e:

function addAreas(s1, s2){
    //We can't know for sure if s1 or s2 have a getArea() function before the code is executed
    return s1.getArea() + s2.getArea();
}

To test if an object have a specific function, we can do the following:

function isShape(obj){
    return obj.implements("getArea") && obj.implements("getPerimeter");
}

Both can be combined into the following:

function addAreas(s1, s2){
    if(isShape(s1) && isShape(s2))
        return s1.getArea() + s2.getArea();

    throw "s1 or s2 are not a shape!"
}

Here you can find a great blog post on the subject.

In your example, both your implementations should have a getKey and putKey functions, and the code which expects an object with those functions must test if they were implemented before executing.

Upvotes: 1

Related Questions