Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created July 17, 2021 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikoheikkila/0957cf29ca6f9e9f8651b849f0826c0a to your computer and use it in GitHub Desktop.
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.
// 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