ruby - 功能标志最佳实践 : condition inside or outside of a method?

标签 ruby design-patterns feature-detection

<分区>

我们使用功能标志来启用/禁用我们系统中的某些功能。

我与我的同事讨论了向代码本身添加功能标志的标准方法是什么:

考虑以下方法:

def featured_method
  do_this
  do_that
end

我们的代码中大约有 15 个不同的地方调用了该方法。

您是否建议在每次调用此方法之前添加检查功能是否已启用:

if feature_enabled?(:feature_key)
  featured_method
end

或者在 featured_method 本身内部,像这样:

def featured_method
  if feature_enabled?(:feature_key)
    do_this
    do_that
  end
end

在方法本身内部设置条件的优势很明显:让代码变干,而且当您想永久添加该功能时,只需从方法中删除条件即可。

在每次调用之前设置条件的好处是,无需进入 featured_method 代码本身,就可以非常清楚该方法是否执行,这可以省去很多麻烦。

我想知道是否有针对此类问题的另一种解决方案或标准。

最佳答案

我会合并这两种方法。

这会导致调用方出现 DRY 代码。它不会违反 feature_method 中的 SRP,并且会清楚地传达正在发生的事情 - 如果你能找到比我更好的名字:

def may_execute_featured_method
  featured_method if feature_enabled?(:feature_key)
end

def featured_method
  do_this
  do_that
end

调用者将使用may_execute_featured_method

关于ruby - 功能标志最佳实践 : condition inside or outside of a method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16540947/

相关文章:

c++ - 这是什么设计模式?

c# - 如何允许对私有(private)集合进行迭代但不允许修改?

java - 在 Android 中显示图像上的关键点 - OpenCV

opencv - 使用 ORB 的不稳定单应性估计

Ruby:内核#`运行命令的权限被拒绝

ruby - RSpec 模拟 :each block

java - 最适合康威生命游戏的设计模式

opencv - OpenCV中的相位相关和模板匹配有什么区别?

javascript - Bootstrap 表单如何绑定(bind)到 Rails 模型?

ruby - 将绝对路径与 Pathname 类连接起来