很难选择合适的变量名称

问题描述 投票:0回答:2

我主要使用 JS 进行开发,但自从 React 和他的朋友进入我的生活以来,我觉得我正在编写更多的变量名,比以前多,而且我在命名它们时遇到了麻烦。

通常会尝试选择一些我能记住并且其他人也能记住的东西,同时尽量保持逻辑性并且不要太长。

因此,例如在消息传递应用程序中,

user
可能代表
logged in user
recipient user
user API

我所做的通常是指系统中的任何其他用户。

user
指的是已登录的用户。 API 取决于...
你做什么?是不是应该使用驼峰命名法并带有长变量名?

userLoggedIn、userRecepient、userAPI 等?有没有我可以参考的常用模式或来源(书籍、社区等)?

language-agnostic naming-conventions conventions
2个回答
1
投票
loggedInUser

currentUserrecipientUser。在这种情况下,我不会推荐名称 userLoggedIn 因为它听起来像一个真值(布尔变量)。对于布尔变量,我首先考虑一个形容词并在其前面添加名词。 命名变量是计算机科学中最难的问题之一,因此在命名变量时感到困难也就不足为奇了。


0
投票
me

-> 不幸的是,没有通用的结构可以做到这一点。这取决于您的项目和您的经验。

作为一名拥有 4 年开发经验的开发人员,我可以向您分享一些技巧:


Is there a commonly used pattern or a source (book, community, etc.) that I can look up to?
    想象一下,你是项目中的新人,当你看到变量或函数时,你一定明白这个函数是做什么的。
  1. Don't make the name too abstract.
  2. Always use the verb as the first in the function
  3. 例如:

Use the "has/have" with noun and "is" with adjective

 - "hasSavedRow", not "isSavedRow"
 - "isSelected", not "hasSelected"
  1. Apply the PascalCase for interface, namespace, component, type.
© www.soinside.com 2019 - 2024. All rights reserved.