问题
I want to write code that others easily can understand as well.
Do boolean attributes like hide_email
or email_hidden
have a convention style?
回答1:
I think of it like this:
- 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 justemail_hidden
So, for your specific case, name your attribute like this:
- Start with the question "email is hidden"?. Which can be represented in code as:
email_is_hidden
. - Remove the
is
and you're left withemail_hidden
- Ruby on Rails defines a "predicate" version (one that ends in a
?
) of your boolean attribute and returnstrue
/false
as expected. So, while your attribute is namedemail_hidden
in the database you should reference it asemail_hidden?
in your code for clarity and as is the Ruby on Rails convention.
回答2:
That would be email_hidden?
. It is what Ruby community got used to.
Please note the ?
at the end.
回答3:
The ruby code smeels said that all boolean methods should finish with ?
On active record you could see
User.valid?
Or in ruby you could find
[].nil?
[].empty?
If you want to know about Ruby's conventions read this
http://blogs.visoftinc.com/2010/04/12/ruby-beauty-method-naming-conventions/
回答4:
Taking these two examples of names you gave:
hide_email
would be a good name for a method performing such a task, a method that executes all the procedures to hide an email in the scope of your system. But it would never be a good name for a boolean method returning the state of an e-mail.email_hidden?
, with a question mark (?) at the end, would be the correct name for a boolean method indicating if the e-mail is hidden or not.
Always consider Ruby conventions if you really want to write good code. They will help you even when thinking about the processes in your system.
来源:https://stackoverflow.com/questions/37059547/naming-conventions-for-boolean-attributes