Skip to content

Instantly share code, notes, and snippets.

@hiroshiro
Created February 28, 2014 19:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiroshiro/95632194ab2b408d34b7 to your computer and use it in GitHub Desktop.
Save hiroshiro/95632194ab2b408d34b7 to your computer and use it in GitHub Desktop.
制御構文の条件式ネストを避けるガード節の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
Copy link
Author

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
Copy link
Author

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

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