Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active January 16, 2019 10:45
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 krisleech/65e7bdb3796efeeea2c9863eea8a6603 to your computer and use it in GitHub Desktop.
Save krisleech/65e7bdb3796efeeea2c9863eea8a6603 to your computer and use it in GitHub Desktop.
Where to put `if`, shallow or deeper?
# Lets say we have a Book model and we want to fetch some data about the book from an API and store it in the model.
# A Book needs an identifier before it can be fetched from the API. Not all books have an identifier, e.g. it may not have been entered yet.
# Do we silently return in FetchFromApi when the book has no identifer:
class FetchFromApi
def call(book)
return unless record.identifier.present?
# do API call and update record
end
end
# and thus we can pass any book, regardless of it having an identifier or not:
FetchFromApi.call(book)
# Or do we noisely raise:
class FetchFromApi
def call(book)
raise(ArgumentError, "Book does not have an identifier") unless book.identifier.present?
# do API call and update book
end
end
# And only call FetchFromApi if the book has an identifier:
FetchFromApi.call(book) if book.identifier.present?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment