パンくず
内容
適用ケース要約
フィールドに直接アクセスしているが、フィールドとの密結合が不都合になってきている
適用内容要約
フィールドのゲッター/セッターを作り、フィールドにアクセスするときにはそれらだけを使う
適用詳細
クラス内部でフィールドにアクセスする際にgetter、setterを利用すること。
※getter、setterを外部から使用する話とは違うので注意
サンプル
あるクラスに、2つのフィールドがあり、初期化の際にそれぞれに数値を設定します。
合計を求めるメソッドを呼び出すと2つのフィールドに設定した合計値が返却される機能を実装します。
サンプルコード
class EncapsulationBefore attr_accessor:hoge,:hoo def initialize(hoge,hoo) @hoge=hoge @hoo=hoo end def calculate() return @hoge+@hoo end end p EncapsulationBefore.new(5,10).calculate
class EncapsulationBefore attr_reader:hoge,:hoo def initialize(hoge,hoo) @hoge=hoge @hoo=hoo end def calculate() return hoge+hoo end end p EncapsulationBefore.new(5,10).calculate
出力(共通)
15