1
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 1 year has passed since last update.

インスタンス変数の隠蔽

Last updated at Posted at 2022-01-24

##インスタンス変数の隠蔽

  • インスタンス変数はアクセサメソッドで包み、直接参照しないようにする方がよい。
# bad
class Gear
  def initialize(chainring, cog)
    @chainring = chainring
    @cog = cog
  end

  def ratio
    @chainring / @cog.to_f  # ← bad!
  end
end

# good
class Gear
  attr_reader :chainring, :cog

  def initialize(chainring, cog)
    @chainring = chainring
    @cog = cog
  end

  def ratio
    chainring / cog.to_f
  end
end

アクセサメソッドattr_readerを使うと、Rubyが下記のようなラッパーメソッドを定義してくれる。

def cog
  @cog
end

###隠蔽するメリット
インスタンス変数@chainringが何十箇所で使われていた場合、それらすべてを変更しなくてはならない。
しかし、attr_readerで定義していた場合、変更箇所は1つで済む。

##参考

オブジェクト指向設計実践ガイド

1
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
1
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?