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?
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.<p>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:<p><pre><code> IsEntityPersisted()
WasActionPerformed()
IsFooOfTypeBar()
</code></pre>
etc.<p>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:<p><pre><code> entityIsPersisted
actionWasPerformed
fooIsOfTypeBar
</code></pre>
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:<p><pre><code> if(logicFlag)
{
//do something
}
</code></pre>
vs<p><pre><code> if(actionWasPerformed)
{
//do something
}
</code></pre>
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.