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);
if (not entity_exists(entity_id))
!
character so many times causing me to mis-understand the code until I re-read it again. So I probably agree more with your coworker. I like the form that evaluates to true when you examine it.if (!exists) create()
can be seen as a bad practice in many languages/frameworks, as it tends to not be thread-safe. Usually, the preferred approach is to callcreate()
and handle specific exceptions or return codes saying that the entity already exists. This is of course not an answer to the actual question (which is why it is a comment only).