Last active
October 7, 2019 18:38
-
-
Save karloscodes/36d649ff2391d30768d1de0d6e11aa27 to your computer and use it in GitHub Desktop.
Depdency injection OOP vs FP in javascript. A use case for currying. Partial application.
This file contains hidden or 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
// ----------------------------------------------- | |
// OOP dependency injection (the repository implementation can be switched in runtime) | |
// ----------------------------------------------- | |
class UserService { | |
constructor(userRepository) { | |
this.userRepository = userRepository | |
} | |
create(params) { | |
validate(params) | |
return this.userRepository.create(params) | |
} | |
} | |
const mysqlUserRepository = MysqlUserRepository.build(...) | |
const mongoDbUserRepository = MongoDbUserRepository.build(...) | |
const mysqlUserService = new UserService(mysqlUserRepository) | |
const user = mysqlUserService.create({name: 'Carlos'}) | |
const mongoDbUserService = new UserService(mongoDbUserRepository) | |
const anotherUser = mongoDbUserService.create({name: 'Pedro'}) | |
// --------------------------------------------- | |
// FP dependencies with currying v1 | |
// (the function in charge of persistence can be switched in runtime) | |
// --------------------------------------------- | |
function createUser(params) { | |
validate(params) | |
return function(persistFn) { | |
return persistFn(params) | |
} | |
} | |
function persistUserMysql(params) { ... } | |
function persistUserMongoDb(params) { ... } | |
const user = createUser({name: 'Carlos'})(persistUserMysql) | |
const anotherUser = createUser({name: 'Pedro'})(persistUserMongoDb) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment