ruby / Rails 布尔方法命名约定
我有一个关于 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?
的含义相混淆。 因此,第二种方法可能会更清晰,但也更冗长一些。第三个实际上只是为了完整性。我不太喜欢那个。
那么有没有什么公认的良好实践呢?
I have a short question on ruby / rails method naming conventions or good practice.
Consider the following methods:
# 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
So I wonder, which of the three ampersand-methods would be the "best" way to ask for permissions. I would go with the first one somehow, but in some cases I think this might be confused with meaning has_performed_action?
.
So the second approach might make that clearer but is also a bit more verbose. The third one is actually just for completeness. I don't really like that one.
So are there any commonly agreed-on good practices for that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这取决于您想要执行的操作以及您正在检查的操作。我的目标是可读性和最少的混乱:
I think that depends on the action you want to perform and the action you are checking for. I would aim for readability and least amount of confusion:
我不会使用
action?
,因为通常使用单字问号方法来指示值的存在(或不存在)。 Rails 允许您编写类似英语的代码,因此请选择一个使代码最具可读性的方法名称。对我来说似乎完全可读。
I wouldn't use
action?
, because typically, single-word question-mark methods are used to indicate the presence (or absence) of a value. Rails lets you write English-like code, so pick a method name that makes the code the most readable.Seems perfectly readable to me.
我会上升一级并重新考虑原始方法名称。如果这些方法执行一个动作,那么它们扮演的角色是动词,而不是名词:
这对您的问题有一个听起来更自然的答案的便利副作用:
...以及其他一些明显的变体:
等等。
I'd go up one level and rethink the original method names. If the methods perform an action, then the role they play is that of a verb, not a noun:
This has the handy side effect of a more natural-sounding answer to your question:
...as well as some other obvious variants:
Et cetera.