Last active
January 22, 2021 20:56
-
-
Save branneman/9dfc8ed59ea0814d6415 to your computer and use it in GitHub Desktop.
JavaScript Duck typing vs. Interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?