Created
February 28, 2014 19:00
-
-
Save hiroshiro/95632194ab2b408d34b7 to your computer and use it in GitHub Desktop.
制御構文の条件式ネストを避けるガード節のRubyの構文。良い、悪い例。
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
# bad | |
def compute_thing(thing) | |
if thing[:foo] | |
update_with_bar(thing) | |
if thing[:foo][:bar] | |
partial_compute(thing) | |
else | |
re_compute(thing) | |
end | |
end | |
end | |
# good | |
def compute_thing(thing) | |
return unless thing[:foo] | |
update_with_bar(thing[:foo]) | |
return re_compute(thing) unless thing[:foo][:bar] | |
partial_compute(thing) | |
end |
制御構文で条件式のネストは避けましょう。 不正なデータをアサートするにはガード節を好みます。 ガード節は、可能な限り関数から出ていくために、 関数の先頭付近で宣言される条件式です。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Avoid use of nested conditionals for flow of control. Prefer a guard clause when you can assert invalid data. A guard clause is a conditional statement at the top of a function that bails out as soon as it can.