Skip to content

Instantly share code, notes, and snippets.

@fluffybunnies
Created September 28, 2018 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fluffybunnies/7a879a10d69dd9f6a808b7ef6e54d4e9 to your computer and use it in GitHub Desktop.
Save fluffybunnies/7a879a10d69dd9f6a808b7ef6e54d4e9 to your computer and use it in GitHub Desktop.
Factory + Inheritance
'use strict';
class ImportDaoInterface {
/**
This methods contract is x, y, z
*/
getOrders(dateRange, cb) {
throw 'Extend Me!'
}
}
class GrubhubImportDao extends ImportDaoInterface {
getOrders(dateRange, cb) {
process.nextTick(function(){
cb(false, [])
})
}
}
function ImportDaoFactory(whichOne){
//try {
// var importDao = new require('../dao/'+whichOne+'Dao')
//} catch (e) {
// throw new Error('Not Implemented')
//}
// the above for production, but for this all-in-one test case:
var importDao = new GrubhubImportDao
// can do factory things here if want to, like:
var getOrdersWrapper = importDao.getOrders
importDao.getOrders = function(dateRange,cb){
getOrdersWrapper(dateRange,function(err,orders){
if (err) {
console.log('report error to sentry, etc')
}
cb(err,orders)
})
}
return importDao
}
// test...
ImportDaoFactory('GrubhubImport').getOrders('last 3 hours', function(err,orders){
console.log('orders=',orders)
})
@langal
Copy link

langal commented Sep 28, 2018

Thats really cool.

@fluffybunnies
Copy link
Author

fluffybunnies commented Sep 28, 2018

And can always add properties/attrs like:

function ImportDaoFactory(whichOne, props){
    try {
        var importDao = new (require('../dao/'+whichOne+'Dao')(props))
    } catch (e) {
        throw new Error('Not Implemented')
    }

But I am against that cuz imho the instantiator should not know init values of a DAO/Adapter/whatever. That should be controlled by configs (or a separate class). It conflates responsibilities. Consider example where we leverage factory to cache instances and/or responses (to account for read slave lag)

@dbercht
Copy link

dbercht commented Sep 28, 2018

I like the inheritance pattern with the caveat of:

  1. Dynamically loading classes based on a string at runtime

The second thing is that the ImportDaoFactory will be super repetitive. You should be able to abstract away what interface you define for the DAO and the autoloading of the class. I'll get a revised version of it in a sec

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