Function Naming – Affirmative vs Negative Boolean Methods

functionsnaming

Should boolean methods always take the affirmative form, even when they will only ever be used in the negative form?

Say I wanted to check whether an entity exists before creating one, my argument is that the first form below is better than the second form, whether or not the method is ever used in the affirmative form.

In summary, I find if(!affirmative) easier to read than if(negative). I have a colleague who disagrees, thoughts?

First Form:

int entity_id = 42;
if(!entity_exists(entity_id)) create_entity(entity_id);

Second Form:

int entity_id = 42;
if(entity_not_exist(entity_id)) create_entity(entity_id);

Best Answer

Should boolean methods always take the affirmative form, even when they will only ever be used in the negative form?

Making rules about such things seems a little much -- I wouldn't want to see a guideline in a coding standards document that says thou shalt not use negative names for boolean properties. But as a matter of personal style, I think trying to keep the names positive could be a fine ideal. However, I think it's also good to avoid the need for that skinny and easily-missed !. One can often find ways to turn a negative name into a positive one:

  • accountHasCharges
  • accountIsClear (same as !accountHasCharges)

Clarity is the most important consideration, and a good reason for avoiding negative method names is that they can lead to double negatives or worse:

  • isComplete // okay
  • isNotComplete // !isComplete is usually better
  • isIncomplete // could make sense if 'incomplete' is a known state of the object
  • !isNotComplete // horrible
  • !isNotComplete == 0 // may lead to permanent vacation