TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Best practice for naming a Boolean variable or method

4 点作者 yllow大约 10 年前
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?

1 comment

chton大约 10 年前
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&#x27;re writing.<p>If it&#x27;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&#x27;d set it to true or false, not for how you intend to use it. Compare:<p><pre><code> if(logicFlag) { &#x2F;&#x2F;do something } </code></pre> vs<p><pre><code> if(actionWasPerformed) { &#x2F;&#x2F;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 &quot;what something means&quot; and &quot;what something does in the application&quot;. If you manage to make the meaning clear, the reasons for what it does will become clearer too. The reverse is rarely the case.
评论 #9353264 未加载