布尔属性的命名约定 [英] Naming conventions for boolean attributes

查看:81
本文介绍了布尔属性的命名约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写别人也容易理解的代码.

I want to write code that others easily can understand as well.

hide_emailemail_hidden这样的布尔属性是否具有约定样式?

Do boolean attributes like hide_email or email_hidden have a convention style?

推荐答案

我是这样想的:

  • 布尔值属性应回答一个简单的是/否问题.
  • 问是?"是询问是/否问题的简单方法.
  • 因此,布尔属性名称应使句子is <attribute_name>
  • 完整
  • 然后只需删除is,因为Ruby倾向于使用?后缀来表示"is"样式的方法名(请参见下文以获取更多信息),而只剩下email_hidden
  • A boolean attribute should answer a simple yes/no question.
  • Asking "is?" is a simple way to ask a yes/no question.
  • So a boolean attribute name should complete the sentence is <attribute_name>
  • Then just remove the is because Ruby prefers the ? suffix for "is"-style method names (see below for more), leaving you with just email_hidden

因此,对于您的特定情况,请按以下方式命名您的属性:

So, for your specific case, name your attribute like this:

  • 从问题电子邮件已隐藏"开始.可以用代码表示为:email_is_hidden.
  • 删除is,然后剩下email_hidden
  • Ruby on Rails定义了布尔属性的谓词"版本(以?结尾),并按预期返回true/false.因此,尽管在数据库中将属性命名为email_hidden,但为了清楚起见,应在代码中将其引用为email_hidden?,并且在Ruby on Rails约定中也应将其引用.
  • Start with the question "email is hidden"?. Which can be represented in code as: email_is_hidden.
  • Remove the is and you're left with email_hidden
  • Ruby on Rails defines a "predicate" version (one that ends in a ?) of your boolean attribute and returns true/false as expected. So, while your attribute is named email_hidden in the database you should reference it as email_hidden? in your code for clarity and as is the Ruby on Rails convention.

这篇关于布尔属性的命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆