August 2014
Intermediate to advanced
120 pages
2h 45m
English
If you’ve programmed in an imperative language, chances are you’ve used a guard clause to return early from a method or function in certain cases, like the following Ruby code that approximates following someone on Twitter:
| control_flow/guard_clause.rb | |
| | def follow_user(user, user_to_follow) |
| | if user_to_follow.blocked?(user) |
| | puts "#{user_to_follow.name} has blocked #{user.name}" |
| | return |
| | end |
| | user.following << user_to_follow |
| | user_to_follow.followers << user |
| | end |
Early returns can be confusing if we use them all over the place, but they can be useful to describe requirements for the main method body to execute. Normally in Clojure, we’d need to write something like this:
| control_flow/guard_clause_1.clj ... |
Read now
Unlock full access