布尔变量起名

来源:https://thatamazingprogrammer.com/posts/stop-naming-your-variables-flag-the-art-of-boolean-prefixes/

  • IS:身份与状态使用,用于描述某事物当前的状态。通常与形容词搭配使用。

    • 好: isActive, isDeleted, isEmpty.
    • 差: isAccess (Grammar mismatch. Use hasAccess).
  • HAS:表示拥有或包含关系,通常与名词搭配使用。

    • 好: hasAccess, hasChildren, hasValidationErrors.
    • 差: hasActive (Grammar mismatch. Use isActive).
  • CAN:能力使用可以检查权限或潜在操作。

    • 好: canEdit, canDelete, canRetry.
    • 差: canAdmin (Vague. Use isAdmin or canAdminister).
  • SHOULD:应将“意图使用”用于系统需要做出的业务规则或决策。这将“我们能够做什么”与“我们希望做什么”区分开来。

    • 好: shouldRetry, shouldCacheResponse.
    • 差: shouldUser (Incomplete. shouldCreateUser?).

另一条规则:永远不在布尔变量名中使用否定词。

posted @ 2026-07-23 13:59  Joeyin  阅读(7)  评论(0)    收藏  举报