LoginSignup
0
0

More than 3 years have passed since last update.

クラスの依存関係を明確にする

Last updated at Posted at 2021-04-09

某参考書を読んでいて参考になった箇所があったのでメモ。(記載のソースは自作のもの)

例えば、以下のようなコードでは、FruitクラスはAppleクラスが存在することを知っている(依存している)。
かつ、それが「Fruitクラスのfruit_nameメソッドの中」という深い場所で発生してしまっているので、一見して気づきにくい。

class Fruit
  def fruit_name
    Apple.new.name
  end
end

class Apple
  def name
    puts "Apple"
  end
end

Fruit.new.fruit_name

これだと一見依存を見つけにくいので、以下のようにすると明らかにしやすい。

class Fruit
  def fruit_name
    apple.name
  end

  def apple
    Apple.new
  end
end

class Apple
  def name
    puts "Apple"
  end
end

Fruit.new.fruit_name

あるいは以下のようにinitializeで定義してもいい

class Fruit
  attr_reader :apple
  def initialize
    @apple = Apple.new
  end

  def fruit_name
    apple.name
  end
end

class Apple
  def name
    puts "Apple"
  end
end

Fruit.new.fruit_name

そもそもFruitがAppleを知っているのが良くないみたいだが、そこについてはこれから勉強...

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