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?
✔️ DO name Boolean properties with an affirmative phrase ( CanSeek instead of CantSeek ). Optionally, you can also prefix Boolean properties with "Is", "Can", or "Has", but only where it adds value. ✔️ CONSIDER giving a property the same name as its type.
Boolean variables should be prefixed with 'is' This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag.
A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ".
I think of it like this:
is <attribute_name>
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
and you're left with email_hidden
?
) 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.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.
That would be email_hidden?
. It is what Ruby community got used to.
Please note the ?
at the end.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With