
Best practice for naming a Boolean variable or method - yllow
I have read about flag is a trap. But sometimes using a Boolean is unavoidable. What is the best practice for the naming convention , to make it meaningful to  read yet not confusing?
======
chton
The best practices are going to be somewhat language-dependent. In general,
the least confusing style is the one that is already used widely in the
application you're writing.

If it's up to me to decide a naming system (I mostly do C# professionally), my
boolean-returning methods will be in the form of a tiny question that has a
yes or no answer:

    
    
        IsEntityPersisted()
        WasActionPerformed()
        IsFooOfTypeBar()
    

etc.

For variables, local values and method parameters, the names will be similar,
but in the form of a true or false statement. The equivalent would then be:

    
    
        entityIsPersisted
        actionWasPerformed
        fooIsOfTypeBar
    

The important thing in both cases is to name the boolean for what it means,
why you'd set it to true or false, not for how you intend to use it. Compare:

    
    
        if(logicFlag)
        { 
         //do something
        }
    

vs

    
    
        if(actionWasPerformed) 
        { 
         //do something
        }
    

Clarity in a naming schemes is all about making it clear what something means
in the context. I know that sounds like a tautology, but there is a difference
between "what something means" and "what something does in the application".
If you manage to make the meaning clear, the reasons for what it does will
become clearer too. The reverse is rarely the case.

~~~
ABNWZ
Thank you for this succinct explanation. Very clear!

~~~
chton
My pleasure. One thing I forgot to mention is that I try to never use
negatives in boolean names, both for methods and variables. The moment you
start with "IsNotXXX" or "HasNoXXX", you're creating a new way to potentially
confuse future readers. If you can, always try to find a positive way of
expressing the same, it'll usually be less ambiguous. If it really is
necessary to express a negative, perhaps because the reverse is too broad or
hard to formulate, it's usually better to invert the meaning of the boolean
entirely. So instead of

    
    
        if(IsNotFoo) {}
    

you can do

    
    
       if(!IsFoo) {}
    

It's a simple thing, but it can save you valuable time and brainspace at some
point in the future.

