gpt4 book ai didi

ruby - 测试抽象的 if 条件

转载 作者:行者123 更新时间:2023-11-28 20:26:07 24 4
gpt4 key购买 nike

我正在尝试找出测试 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 个公共(public)方法,因为 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

关于ruby - 测试抽象的 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56654832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com