Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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);
share|improve this question
    
I always use ìsItTheCaseThat...., this greatly enhances readability. –  Ingo May 2 '13 at 15:19
2  
C++? how about if (not entity_exists(entity_id)) –  Kos May 2 '13 at 15:36
add comment

2 Answers

up vote 28 down vote accepted

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
share|improve this answer
2  
"I wouldn't want to see a guideline in a coding standards document that says thou shalt not use negative names for boolean properties." - I'll just leave this here... –  AakashM May 2 '13 at 14:36
6  
+1 for the permanent vacation –  Friek May 3 '13 at 20:10
4  
You forgot !isNotIncomplete –  Ben Lee May 6 '13 at 18:55
add comment

I agree that the affirmative is easier to read. You might try

Third Form

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

or

Fourth Form

int entity_id = 42;
if (is_entity_missing(entity_id)) create_entity(entity_id);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.