Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
制御構文の条件式ネストを避けるガード節のRubyの構文。良い、悪い例。
# 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
@hiroshiro

This comment has been minimized.

Copy link
Owner Author

@hiroshiro hiroshiro commented Feb 28, 2014

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.

@hiroshiro

This comment has been minimized.

Copy link
Owner Author

@hiroshiro hiroshiro commented Aug 14, 2014

制御構文で条件式のネストは避けましょう。 不正なデータをアサートするにはガード節を好みます。 ガード節は、可能な限り関数から出ていくために、 関数の先頭付近で宣言される条件式です。

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