Skip to content

Instantly share code, notes, and snippets.

@waterlink
Created Mar 10, 2015
Embed
What would you like to do?
contracts.ruby :: Non-type checking example
# Classical defensive programming
def do_something_useful(active_user)
return unless active_user.last_action_date < 2.weeks.ago
# do something useful with active user
end
# ----
# With contracts:
Contract ActiveUser => Any
def do_something_useful(active_user)
# do something useful with active user, but it is already a guarantee, that it is active, you don't need to guard against that
end
# Definition of ActiveUser contract (it is not a class of active_user)
class ActiveUser
def self.valid?(user)
active_user.last_action_date < 2.weeks.ago
end
end
@waterlink
Copy link
Author

If you have a need to check for more arguments and a return value in classical defensive programming your code will be a mess

@waterlink
Copy link
Author

With contracts it will look very elegantly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment