【问题标题】:ruby / rails boolean method naming conventionsruby / rails 布尔方法命名约定
【发布时间】:2011-06-24 12:12:33
【问题描述】:

我有一个关于 ruby​​ / rails 方法命名约定或良好实践的简短问题。 考虑以下方法:

# some methods performing some sort of 'action'
def action; end
def action!; end

# some methods checking if performing 'action' is permitted
def action?; end
def can_action?; end
def action_allowed?; end

所以我想知道,三种与号方法中的哪一种是请求权限的“最佳”方式。我会以某种方式使用第一个,但在某些情况下,我认为这可能与has_performed_action? 的含义相混淆。 所以第二种方法可能会更清楚,但也更冗长。第三个实际上只是为了完整性。我不是很喜欢那个。

那么有什么公认的好的做法吗?

【问题讨论】:

  • 我认为最好的选择是代码最易读的时候。在我看来,第三种形式看起来更好。特别是因为我可以阅读“如果 action_allowed?”。或者一个更好的选择(在我看来)是 action_is_allowed?。

标签: ruby-on-rails ruby methods naming-conventions


【解决方案1】:

我认为这取决于您要执行的操作以及您正在检查的操作。我的目标是可读性和最少的混淆:

self.run
self.can_run? # can this object run?
self.running_allowed? # is running allowed here or by this user?

self.redeem!
self.redeemable? # is this object currently redeemable?

self.copy_to_clipboard
self.copy_to_dashboard
self.copyable? or self.can_be_copied? #can this object be copied
self.copy_allowed?(:clipboard) # is copying to the clipboard allowed by me?

【讨论】:

    【解决方案2】:

    我不会使用action?,因为通常使用单字问号方法来指示值的存在(或不存在)。 Rails 允许您编写类似英语的代码,因此请选择一个使代码最易读的方法名称。

    perform_action!("update") if action_allowed?("update")
    

    对我来说似乎完全可读。

    【讨论】:

    • 嗯,action? 这句话似乎有道理。但是,我有点担心的是您可能会使用多种不同的方式来请求津贴。可能是action_allowed?action_permitted?action_authorized?action_granted?。我认为在更大的团队中这可能会成为一个问题,对吗?
    【解决方案3】:

    我会上一层并重新考虑原始方法名称。如果方法执行一个动作,那么它们所扮演的角色是动词,而不是名词:

    # some methods performing some sort of 'action'
    def act
    def act!
    

    这有一个方便的副作用,即更自然地回答您的问题:

    # method checking if 'action' is permitted
    def can_act?
    

    ...以及其他一些明显的变体:

    # methods checking if 'action' was performed
    def acted?
    def did_act?
    
    # method checking if 'action' is called for by other circumstances
    def should_act?
    
    # method putting 'action' into a work queue
    def act_later(delay_seconds=0)
    

    等等。

    【讨论】:

      【解决方案4】:
      def can_action?; end
      

      【讨论】:

        猜你喜欢
        • 2010-11-18
        • 2011-04-21
        • 1970-01-01
        • 2016-08-31
        • 2018-08-31
        • 1970-01-01
        • 2012-04-27
        • 2013-05-21
        相关资源
        最近更新 更多