Last active
August 29, 2015 14:17
-
-
Save ecoologic/9ecf37a5da012d47d534 to your computer and use it in GitHub Desktop.
How to use return statement
This file contains hidden or 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
# One return per line makes it easy to understand / debug | |
def done? | |
return false if no_one_done_it? | |
return false if not_found? | |
return true if you_did_it? | |
false | |
end | |
# Special case pattern (!= NullObject) | |
# Some, including Kent Beck and Martin Fowler argue that one or more guard clauses | |
# -- conditional "early exit" return statements near the beginning of a function -- | |
# often make a function easier to read than the alternative. | |
def do_it | |
return unless @go_for_it | |
# code with no other early return | |
# implicit return | |
end | |
# Default | |
# Single Entry, Single Exit (SESE) | |
# It's the best because it's the simplest flow (*) | |
# Also, when return is used to "return early", it may suffer from the same sort | |
# of problems that arise for the GOTO statement. | |
def make | |
prepare_make | |
if shouldnt_be_made? | |
false | |
elsif can_be_make_easily? | |
simply_make_it! # => [true|false] | |
else | |
try_to_make_it! # => [true|false] | |
end | |
end | |
# The case for node (super-nested code): | |
# Conversely, it can be argued that using the return statement is worthwhile | |
# when the alternative is more convoluted code, such as deeper nesting, harming readability. | |
# * Conditions apply | |
# In the sources: | |
# http://en.wikipedia.org/wiki/Return_statement | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment