Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active January 22, 2021 20:56
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/9dfc8ed59ea0814d6415 to your computer and use it in GitHub Desktop.
Save branneman/9dfc8ed59ea0814d6415 to your computer and use it in GitHub Desktop.
JavaScript Duck typing vs. Interfaces
// Factory
var encrypterFactory = function(config) {
var encrypter = eval('new Encrypt' + config.algorithm.toUpperCase());
if (typeof encrypter.encrypt !== 'function') {
throw new Error(encrypter.constructor.name + ' must implement the `encrypt` method!');
}
return encrypter;
};
// Implementations
class EncryptMD5 {
encrypt(str) { return str.toUpperCase(); }
}
class EncryptROT13 {
// offending: not implementing encrypt() method
}
// Consumer
var str = "imma be encrypted";
encrypterFactory({ algorithm: 'md5' }).encrypt(str); // => Success!
encrypterFactory({ algorithm: 'rot13' }).encrypt(str); // => TypeError: .encrypt is not a function
// Factory
var encrypterFactory = function(config) {
var encrypter = eval('new Encrypt' + config.algorithm.toUpperCase());
if (!(encrypter instanceof Encrypt)) {
throw new Error(encrypter.constructor.name + ' must implement `Encrypt` interface!');
}
return encrypter;
};
// Interface
class Encrypt {
encrypt(str) { throw new TypeError(this.constructor.name + ' must implement the `encrypt` method!'); }
}
// Implementations
class EncryptMD5 extends Encrypt {
encrypt(str) { return str.toUpperCase(); }
}
class EncryptROT13 { // offending: not implementing interface
encrypt(str) { return str.split('').reverse().join(''); }
}
class EncryptSHA256 extends Encrypt {
// offending: not implementing encrypt() method
}
// Consumer
encrypterFactory({ algorithm: 'md5' }).encrypt("encrypt me"); // => Success!
encrypterFactory({ algorithm: 'rot13' }).encrypt("encrypt me"); // => Error: Implement Encrypt interface!
encrypterFactory({ algorithm: 'sha256' }).encrypt("encrypt me"); // => Error: Implement encrypt() function!
@cotnic
Copy link

cotnic commented Jun 5, 2018

Hello, can the check also be done on type of arguments to the functions/methods? So in case we want to input a new class as a parameter for encrypt function, how can we check that it's the type of that function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment