Last active
January 16, 2019 10:45
-
-
Save krisleech/65e7bdb3796efeeea2c9863eea8a6603 to your computer and use it in GitHub Desktop.
Where to put `if`, shallow or deeper?
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
# 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