0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】メソッド名を付けるときに気をつけること

Posted at

最近、1つのメソッドで色々なことをしてしまってるメソッドのリファクタリングをしていて、
その過程で処理ごとにメソッドに切り出すことが多く、
メソッド名の付け方で迷うことがあったのでまとめてみる。

オブジェクトを別の形に変換するメソッド名はto_hogeにする

# hashにして返すメソッド
# 悪くはない例
def convert_to_hash
end

# より良い例
def to_hash
end

否定形のメソッド名はなるべく作らない

判定が複雑になると可読性が下がってしまうこともある。
否定形のメソッドを作りたくなったときは、逆の意味(肯定)のメソッドを作って!hogeの形にして使う。

# 良くない例
book.not_published?

# 良い例
!book.published?

判定形のメソッドの末尾には疑問符?をつける

trueかfalseを返すメソッドの末尾にだけ「?」をつける。それ以外にはつけない。

shop.open?

メソッド名に疑問符をつけられるのはRubyだけらしい。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?