Friday, April 27, 2012

Good practice when naming a Boolean variable/Property

schema_boolean<soapbox>

When defining a Boolean (true/false) variable or property

  1. Prefix the name with "Is" or "Has"
  2. Do not negate in your variable name.

Bad Boolean variables names:

  • Allowed (No prefix)
  • IsNonUser (Negated Name)
  • IsNotAllowed (Negated Name)
  • Permission (No prefix)

Good boolean variable names:

  • IsAllowed
  • IsUser
  • IsAllowed
  • HasPermission

Why?

Because if statements with negation become easier to read.

I think this if statement is harder to read

   1: if(!IsNotAllowed) 
   2: { 
   3:     ShareCandy(); // "If not is not allowed then share candy"
   4: } 

Then this if statement

   1: if(IsAllowed) 
   2: { 
   3:     ShareCandy(); // "If is allowed then share candy"
   4: } 

</soapbox>

2 comments: