如何放弃对类方法的依赖

时间:2014-10-27 11:35:12

标签: ruby dependency-injection dependencies decoupling

我有以下3个课程:

module TitleSource

  class Base
    include Comparable

    attr_accessor :company
    attr_accessor :priority
    attr_accessor :target_title

    def initialize(args={})
      self.company = args[:company]
      self.priority = args[:priority]
      self.target_title = args[:target_title]
    end

    def create_contact_source
      raise NotImplementedError
    end

    def <=>(other)
      fetch_value <=> other.fetch_value
    end

    protected def fetch_value
      value
    end

    private def value
      raise NotImplementedError
    end

  end

end

UnmatchedTitle

module TitleSource

  class UnmatchedTitle < Base

    def create_contact_source
      ::ContractorUi::ContactSource.generate_from_unmatched_title(self)
    end

    private def value
      100
    end

  end

end

IncompleteContact

module TitleSource

  class IncompleteContact < Base

    attr_accessor :target_title_name
    attr_accessor :contact

    def initialize(args={})
      super
      self.target_title_name = args[:target_title_name]
      self.contact = args[:contact]
    end

    def create_contact_source
      ::ContractorUi::ContactSource.generate_from_incomplete_contact(self)
    end

    private def value
      10
    end

  end

end

我目前正在阅读POODR,并想出了这个设计,到目前为止我一直都很好。
但是,出于教学原因,我想知道如果它值得,我应该如何删除对::ContractorUi::ContactSource的依赖以及是否应该这样做。
我不喜欢用构造函数传递它的想法,因为TitleSource模块的整个目的是实际生成ContactSource,但是希望听到更有经验的人的意见。阅读这本书(以及一些现场经验)让我了解脱钩有多重要

1 个答案:

答案 0 :(得分:0)

我可以确认,在这种情况下,只有一个依赖关系不是一个大问题。基于POODR,这段代码可以很好地对变化作出反应,因此在这种情况下保持类依赖性是好的,特别是考虑到它是整个类的主要目的,生成ContactSource的实例

相关问题