Created
July 17, 2021 14:22
-
-
Save nikoheikkila/0957cf29ca6f9e9f8651b849f0826c0a to your computer and use it in GitHub Desktop.
A simple example of refactoring a function in baby steps from returning to boolean all the way to Either monad.
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
// Option 1: true or false to indicate success | |
function createUser(id: string): boolean { | |
const user = User.getById(id); | |
if (!user) { | |
User.create(id); | |
return true; | |
} | |
return false; | |
} | |
// Option 2: null on failure or User object on success | |
function createUser(id: string): User | null { | |
const user = User.getById(id); | |
if (!user) { | |
return User.create(id); | |
} | |
return null; | |
} | |
// Option 3: a Maybe monad with Nothing for failure and Just for success | |
function createUser(id: string): Maybe<User> { | |
const user = User.getById(id); | |
if (!user) { | |
return Just(User.create(id)); | |
} | |
return Nothing; | |
} | |
// Option 4: an Either monad with Left for failure and Right for success | |
function createUser(id: string): Either<ModelError, User> { | |
const user = User.getById(id); | |
if (!user) { | |
return Right(User.create(id)); | |
} | |
return Left(new ModelError(`User with ID ${id} already exists`)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment