Skip to content

Instantly share code, notes, and snippets.

@arastu
Last active August 21, 2018 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arastu/562f5b6503e80d2bcf40ebb209400933 to your computer and use it in GitHub Desktop.
Save arastu/562f5b6503e80d2bcf40ebb209400933 to your computer and use it in GitHub Desktop.
If it looks like a duck and quacks like a duck, it's a duck
// This is a classical example of dependency injection.
// My class Car receives an instance of an engine and use it in the run method, where it calls the turnOn method.
// Note that my Car does not depends on any concrete implementation of engine.
// And I'm not importing any other type! Just using a dependency injected instance of something
// that responds to a turn_on message. I could say my class Car depends on an interface.
// But I did not have to declare it. It is an automatic interface!
class Car {
constructor(engine) {
this.engine = engine
}
run() {
this.engine.turnOn()
}
}
// In a language without duck typing I'll probably have to declare an explicit interface named for example IEngine,
// have the implementation (for example EngineV1)
// and explicit define my Car parameter to be an implementation of IEngine.
//
// interface IEngine {
// void turnOn();
// }
// public class EngineV1 implements IEngine {
// public void turnOn() {
// // do something here
// }
// }
// public class Car {
// public Car(IEngine engine) {
// this.engine = engine;
// }
// public void run() {
// this.engine.turnOn();
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment