Interfaces

Interfaces

An interface is a contract that defines the properties and what the object that implements it can do. For example, you could define what can do a Plumber and an Electrician:
interface Electrician {
  layWires(): void
}

interface Plumber {
  layPipes(): void
}
Then, you can consume the services of your interfaces:
function restoreHouse(e: Electrician, p: Plumber) {
  e.layWires()
  p.layPipes()
}
Notice that the way you have to implement an interface is free. You can do that by instantiating a class, or with a simple object:
let iAmAnElectrician = {
  layWires: () => { console.log("Work with wires…") }
}
An interface doesn't exist at all at runtime, so it is not possible to make an introspection. It is the classic JavaScript way to deal with object programming, but with a good control at compile time of the defined contracts.


4
Imagine that the functionality of B is to write a log to some database. The class B depends on the functionality of the class DB and provides some interface for its logging functionality to other classes.
Class A needs the logging functionality of B, but is does not care, where the log is written to. It does not care for DB, but since it depends on B, it also depends on DB. This is not very desirable.
So what you can do, is to split the class B into two classes: An abstract class L describing the logging functionality (and not depending on DB), and the implementation depending on DB.
Then you can decouple the class A from B, because now A will only depend on LB now also depends on L, that is why it is called dependency inversion, because B provides the functionality offered in L.
Since A now depends on just a lean L, you can easily use it with other logging mechanism, not depending on DB. E.g. you can create a simple console based logger, implementing the interface defined in L.
But since now A does not depend on B but (in sources) only on the abstract interface L at run time it has to be set up to use some specific implementation of L (B for instance). So there needs to be somebody else that tells A to use B (or something else) during the runtime. And that is called inversion of control, because before A decided to use B, but now somebody else (e.g. a container) tells A to use B during the runtime.

Comments

Popular Posts