如果有条件则测试摘要

全白

我正在尝试找出在find_communities此处进行测试的最佳方法,而不必在这里使用多态性来击败if盯着我语句。

class CommunityFinder
  def initialize(filters={})
    @filters = filters
  end

  def find_communities
     return my_communities if @filters[:my_communities]
     visible_communities
  end

  def my_communities
     # [...]
  end

  def visibile_communities
     # [...]
  end
end

我都my_communitiesvisible_communities行之有效的,但我对测试的担忧find_communities

  1. 我不想重复测试设置既my_communitiesvisible_communities,因为有可能将是
  2. 我希望类API包含所有3个公共方法,因为条件find_communities永远不会改变。
  3. 我写这篇文章的期望是在不久的将来班级将由我以外的其他人更改,并且将会有更多的方法

我是不是该:

  1. find_communities生活在主叫
  2. 成为find_communities自己的策略
  3. 将测试复制到 find_communities
  4. 选择您自己的第四个选项。
塔德曼

在本示例中,您确实应该有两个子类,每个子类实现自己的communities方法:

class CommunityFinder::Base
  def initialize(**options)
    @options = options
  end
end

class CommunityFinder::Mine < CommunityFinder::Base
  def communities
  end
end

class CommunityFinder::Visible < CommunityFinder::Base
  def communities
  end
end

您可以使用工厂方法来实例化正确的子类:

module CommunityFinder
  def self.filter(**options)
    if (options[:my_communities])
      CommunityFinder::Mine.new(options)
    else
      CommunityFinder::Visible.new(options)
    end
  end
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章