命名规范

https://www.zhihu.com/question/21440067

作者:何新宇
链接:https://www.zhihu.com/question/21440067/answer/24522844
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文地址:15 Best Practices of Variable & Method Naming


  1. 不同的代码段采用不同的命名长度。通常来说,循环计数器(loop counters)采用1位的单字符来命名,循环判断变量(condition/loop variables)采用1个单词来命名,方法采用1-2个单词命名,类采用2-3个单词命名,全局变量采用3-4个单词命名。
  2. 对变量采用具体的命名(specific names)方式,”value”, “equals”, “data”在任何情况下都不是一种有效的命名方式。
  3. 采用有意义的命名(meaningful names)。变量的名字必须准确反映它的含义和内容。
  4. 不要用 o_, obj_, m_ 等前缀命名。变量不需要前缀标签来表示自己是一个变量。
  5. 遵循公司的变量命名规则,在项目中坚持使用同一种变量命名方式。例如txtUserName, lblUserName, cmbSchoolType等,否则会对可读性造成影响,而且会令查找/替换工具(find/replace tools)不可用。
  6. 遵循当前语言的变量命名规则,不要不统一(inconsistently)地使用大/小写字母。例如:userName, UserName, USER_NAME, m_userName, username, …。
    以Java为例:
    * 类名使用驼峰命名法(Camel Case):VelocityResponseWriter
    * 包名使用小写:com.company.project.ui
    * 变量使用首字母小写的驼峰命名法(Mixed Case):studentName
    * 常量使用大写:MAX_PARAMETER_COUNT = 100
    * 枚举类(enum class)采用驼峰命名法,枚举值(enum values)采用大写。
    * 除了常量和枚举值以外,不要使用下划线’_’
  7. 在同一个类不同的场景(contexts)中不要复用变量名。例如在方法、初始化方法和类中。这样做可以提高可读性和可维护性。
  8. 不要对不同使用目的的变量使用同一个变量名,而是赋予它们不同的名字。这同样对保持可读性和可维护性很重要。
  9. 变量名不要使用非ASCII字符(non-ASCII chars)。这样做可能会在跨平台使用时产生问题。
  10. 不要使用过长的变量名(例如50个字符)。过长的变量名会导致代码丑陋(ugly)和难以阅读(hard-to-read),还可能因为字符限制在某些编译器上存在兼容性问题。
  11. 仅使用一种自然语言(natural language)来命名变量。例如,同时使用德语和英语来命名变量会导致(理解)不一致和降低可读性。
  12. 使用有意义的方法名。方法名必须准确表达该方法的行为,在多数情况下以动词(verb)开头。(例如:createPasswordHash)
  13. 遵循公司的方法命名规则,在项目中坚持使用同一种方法命名方式。例如 getTxtUserName(), getLblUserName(), isStudentApproved(),否则会对可读性造成影响,而且会令查找/替换工具不可用。
  14. 遵循当前语言的变量命名规则,不要不统一地使用大/小写字母。例如:getUserName, GetUserName, getusername, …。
    以Java为例:
    * 方法使用首字母小写的驼峰命名法:getStudentSchoolType
    * 方法参数使用首字母小写的驼峰命名法:setSchoolName(String schoolName)
  15. 使用有意义的方法参数命名,这样做可以在没有文档的情况下尽量做到“自解释(documentate itself)”
 
作者:JavaGuide
链接:https://www.zhihu.com/question/21440067/answer/1277465532
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

为什么需要重视命名?

好的命名即是注释,别人一看到你的命名就知道你的变量、方法或者类是做什么的! 好的命名对于其他人(包括你自己)理解你的代码有着很大的帮助!

简单举个例子说明一下命名的重要性。

《Clean Code》这本书明确指出:

好的代码本身就是注释,我们要尽量规范和美化自己的代码来减少不必要的注释。
若编程语言足够有表达力,就不需要注释,尽量通过代码来阐述。
举个例子:
去掉下面复杂的注释,只需要创建一个与注释所言同一事物的函数即可
// check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))

应替换为
if (employee.isEligibleForFullBenefits())

常见命名规则以及适用场景

这里只介绍 3 种最常见的命名规范。

驼峰命名法(CamelCase)

驼峰命名法应该我们最常见的一个,这种命名方式使用大小写混合的格式来区别各个单词,并且单词之间不使用空格隔开或者连接字符连接的命名方式

大驼峰命名法(CamelCase)

类名需要使用大驼峰命名法(UpperCamelCase)

正例:

ServiceDiscovery、ServiceInstance、LruCacheFactory

反例:

serviceDiscovery、Serviceinstance、LRUCacheFactory

小驼峰命名法(lowerCamelCase)

方法名、参数名、成员变量、局部变量需要使用小驼峰命名法(lowerCamelCase)。

正例:

getUserInfo()、createCustomThreadPool()、setNameFormat(String nameFormat)
Uservice userService;

反例:

GetUserInfo()、CreateCustomThreadPool()、setNameFormat(String NameFormat)
Uservice user_service

蛇形命名法(snake_case)

测试方法名、常量、枚举名称需要使用蛇形命名法(snake_case)

在蛇形命名法中,各个单词之间通过下划线“_”连接,比如should_get_200_status_code_when_request_is_validCLIENT_CONNECT_SERVER_FAILURE

蛇形命名法的优势是命名所需要的单词比较多的时候,比如我把上面的命名通过小驼峰命名法给大家看一下:“shouldGet200StatusCodoWhenRequestIsValid”。感觉如何? 相比于使用蛇形命名法(snake_case)来说是不是不那么易读?**

正例:

@Test
void should_get_200_status_code_when_request_is_valid() {
  ......
}

反例:

@Test
void shouldGet200StatusCodoWhenRequestIsValid() {
  ......
}

串式命名法(kebab-case)

在串式命名法中,各个单词之间通过下划线“-”连接,比如dubbo-registry

建议项目文件夹名称使用串式命名法(kebab-case),比如 dubbo 项目的各个模块的命名是下面这样的。

常见命名规范

Java 语言基本命名规范

1.类名需要使用大驼峰命名法(UpperCamelCase)风格。方法名、参数名、成员变量、局部变量需要使用小驼峰命名法(lowerCamelCase)。

2.测试方法名、常量、枚举名称需要使用蛇形命名法(snake_case),比如should_get_200_status_code_when_request_is_validCLIENT_CONNECT_SERVER_FAILURE。并且,测试方法名称要求全部小写,常量以及枚举名称需要全部大写。

3.项目文件夹名称使用串式命名法(kebab-case),比如dubbo-registry

4.包名统一使用小写,尽量使用单个名词作为包名,各个单词通过 "." 分隔符连接,并且各个单词必须为单数。

正例: org.apache.dubbo.common.threadlocal

反例: org.apache.dubbo.common.threadLocal

5.抽象类命名使用 Abstract 开头

//为远程传输部分抽象出来的一个抽象类(出处:Dubbo源码)
public abstract class AbstractClient extends AbstractEndpoint implements Client {

}

6.异常类命名使用 Exception 结尾。

//自定义的 NoSuchMethodException(出处:Dubbo源码)
public class NoSuchMethodException extends RuntimeException {
    private static final long serialVersionUID = -2725364246023268766L;

    public NoSuchMethodException() {
        super();
    }

    public NoSuchMethodException(String msg) {
        super(msg);
    }
}

7.测试类命名以它要测试的类的名称开始,以 Test 结尾。

//为 AnnotationUtils 类写的测试类(出处:Dubbo源码)
public class AnnotationUtilsTest {
  ......
}

POJO 类中布尔类型的变量,都不要加 is 前缀,否则部分框架解析会引起序列化错误。

如果模块、接口、类、方法使用了设计模式,在命名时需体现出具体模式。

命名易读性规范

1.为了能让命名更加易懂和易读,尽量不要缩写/简写单词,除非这些单词已经被公认可以被这样缩写/简写。比如 CustomThreadFactory 不可以被写成 ~~CustomTF

2.命名不像函数一样要尽量追求短,可读性强的名字优先于简短的名字,虽然可读性强的名字会比较长一点。 这个对应我们上面说的第 1 点。

3.避免无意义的命名,你起的每一个名字都要能表明意思。

正例:UserService userService; int userCount;

反例: UserService service int count

4.避免命名过长(50 个字符以内最好),过长的命名难以阅读并且丑陋。

5.不要使用拼音,更不要使用中文。 注意:像 alibaba 、wuhan、taobao 这种国际通用名词可以当做英文来看待。

正例:discount

反例:dazhe

Codelf:变量命名神器?

这是一个由国人开发的网站,网上有很多人称其为变量命名神器, Guide 在实际使用了几天之后感觉没那么好用。小伙伴们可以自行体验一下,然后再给出自己的判断。

google-styleguide - Style guides for Google-originated open-source projects

这个项目收录了 Google 的几种语言的编码风格推荐。

其他推荐阅读

  1. 《阿里巴巴 Java 开发手册》
  2. 《Clean Code》
  3. Google Java 代码指南:

https://google.github.io/styleguide/javaguide.html#s5.2-specific-identifier-names

5 Naming

5.1 Rules common to all identifiers

Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores. Thus each valid identifier name is matched by the regular expression w+ .

In Google Style, special prefixes or suffixes are not used. For example, these names are not Google Style: name_mNames_name and kName.

5.2 Rules by identifier type

5.2.1 Package names

Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, com.example.deepspace, not com.example.deepSpace or com.example.deep_space.

5.2.2 Class names

Class names are written in UpperCamelCase.

Class names are typically nouns or noun phrases. For example, Character or ImmutableList. Interface names may also be nouns or noun phrases (for example, List), but may sometimes be adjectives or adjective phrases instead (for example, Readable).

There are no specific rules or even well-established conventions for naming annotation types.

Test classes are named starting with the name of the class they are testing, and ending with Test. For example, HashTest or HashIntegrationTest.

5.2.3 Method names

Method names are written in lowerCamelCase.

Method names are typically verbs or verb phrases. For example, sendMessage or stop.

Underscores may appear in JUnit test method names to separate logical components of the name, with each component written in lowerCamelCase. One typical pattern is <methodUnderTest>_<state>, for example pop_emptyStack. There is no One Correct Way to name test methods.

5.2.4 Constant names

Constant names use CONSTANT_CASE: all uppercase letters, with each word separated from the next by a single underscore. But what is a constant, exactly?

Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. If any of the instance's observable state can change, it is not a constant. Merely intending to never mutate the object is not enough. Examples:

// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }

// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final ImmutableMap<String, SomeMutableType> mutableValues =
    ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};

These names are typically nouns or noun phrases.

5.2.5 Non-constant field names

Non-constant field names (static or otherwise) are written in lowerCamelCase.

These names are typically nouns or noun phrases. For example, computedValues or index.

5.2.6 Parameter names

Parameter names are written in lowerCamelCase.

One-character parameter names in public methods should be avoided.

5.2.7 Local variable names

Local variable names are written in lowerCamelCase.

Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.

5.2.8 Type variable names

Each type variable is named in one of two styles:

  • A single capital letter, optionally followed by a single numeral (such as ETXT2)
  • A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestTFooBarT).

5.3 Camel case: defined

Sometimes there is more than one reasonable way to convert an English phrase into camel case, such as when acronyms or unusual constructs like "IPv6" or "iOS" are present. To improve predictability, Google Style specifies the following (nearly) deterministic scheme.

Beginning with the prose form of the name:

  1. Convert the phrase to plain ASCII and remove any apostrophes. For example, "Müller's algorithm" might become "Muellers algorithm".
  2. Divide this result into words, splitting on spaces and any remaining punctuation (typically hyphens).
    • Recommended: if any word already has a conventional camel-case appearance in common usage, split this into its constituent parts (e.g., "AdWords" becomes "ad words"). Note that a word such as "iOS" is not really in camel case per se; it defies any convention, so this recommendation does not apply.
  3. Now lowercase everything (including acronyms), then uppercase only the first character of:
    • ... each word, to yield upper camel case, or
    • ... each word except the first, to yield lower camel case
  4. Finally, join all the words into a single identifier.

Note that the casing of the original words is almost entirely disregarded. Examples:

Prose formCorrectIncorrect
"XML HTTP request" XmlHttpRequest XMLHTTPRequest
"new customer ID" newCustomerId newCustomerID
"inner stopwatch" innerStopwatch innerStopWatch
"supports IPv6 on iOS?" supportsIpv6OnIos supportsIPv6OnIOS
"YouTube importer" YouTubeImporter
YoutubeImporter*
 

*Acceptable, but not recommended.

Note: Some words are ambiguously hyphenated in the English language: for example "nonempty" and "non-empty" are both correct, so the method names checkNonempty and checkNonEmpty are likewise both correct.

 

https://www.cnblogs.com/arxive/p/6374771.html

 

常用变量命名规则 

一、匈牙利命名法【Hungarian】:  

      广泛应用于象Microsoft Windows这样的环境中。  

      Windows 编程中用到的变量(还包括宏)的命名规则匈牙利命名法,这种命名技术是由一位能干的 Microsoft 程序员查尔斯·西蒙尼(Charles Simonyi) 提出的。   

匈牙利命名法通过在变量名前面加上相应的小写字母的符号标识作为前缀,标识出变量的作用域,类型等。这些符号可以多个同时使用,顺序是先m_(成员变量),再指针,再简单数据类型,再其他。例如:m_lpszStr, 表示指向一个以0字符结尾的字符串的长指针成员变量。   

    匈牙利命名法关键是:标识符的名字以一个或者多个小写字母开头作为前缀;前缀之后的是首字母大写的一个单词或多个单词组合,该单词要指明变量的用途。  

匈牙利命名法中常用的小写字母的前缀:  

前缀类型  

a               数组 (Array)

b               布尔值 (Boolean)

by             字节 (Byte)

c              有符号字符 (Char)

cb            无符号字符 (Char Byte,没有多少人用)

cr             颜色参考值 (ColorRef)

cx,cy         坐标差(长度 ShortInt)  

dw           Double Word  

fn              函数  

h                Handle(句柄)  

i                整型  

l              长整型 (Long Int)

lp             Long Pointer  

m_          类的成员  

n            短整型 (Short Int)

np          Near Pointer  

p            Pointer  

s           字符串型  

sz         以null做结尾的字符串型 (String with Zero End)

w        Word    

二、骆驼命名法【camelCase】

骆驼式命令法,正如它的名称所表示的那样,是指混合使用大小写字母来构成变量和函数的名字。例如,下面是分别用骆驼式命名法和下划线法命名的同一个函数:  

   printEmployeePaychecks();  

    print_employee_paychecks();  

     第一个函数名使用了骆驼式命名法——函数名中的每一个逻辑断点都有一个大写字母来标记;第二个函数名使用了下划线法----函数名中的每一个逻辑断点都有一个下划线来标记。  

    骆驼式命名法近年来越来越流行了,在许多新的函数库和Microsoft 

Windows这样的环境中,它使用得当相多。另一方面,下划线法是c出现后开始流行起来的,在许多旧的程序和UNIX这样的环境中,它的使用非常普遍。   

三、帕斯卡命名法【PascalCase】:  

       与骆驼命名法类似。只不过骆驼命名法是首字母小写,而帕斯卡命名法是首字母大写  

       如:public void               DisplayInfo();               string UserName; 

              二者都是采用了帕斯卡命名法.  

【在C#中,以帕斯卡命名法和骆驼命名法居多。 

在C#中,简单的变量一般用camelCase规则,而比较高级的命名使用PascalCase。 如.net Framework的公共字段及公共属性。】  

简单说  

MyData是一個帕斯卡命名的示例。 myData是一個骆驼命名法。 

iMyData是一個匈牙利命名法,小些说明了变量的类型或者用途。

常量、变量、方法名命名规范

常量、变量命名规范

常量:大写字母、下划线    MAX_VALUE

变量:首字母小写、驼峰原则  parameters

类名:首字母大写、驼峰原则  NeuralNetwork

方法名:首字母小写、驼峰原则 updateParameters()

15 Best Practices of Variable & Method Naming 

  1. Use short enough and long enough variable names in each scope of code. Generally length may be 1 char for loop counters, 1 word for condition/loop variables, 1-2 words for methods, 2-3 words for classes, 3-4 words for globals.
  2. Use specific names for variables, for example "value", "equals", "data", ... are not valid names for any case.
  3. Use meaningful names for variables. Variable name must define the exact explanation of its content.
  4. Don't start variables with o_, obj_, m_ etc. A variable does not need tags stating that it is a variable.
  5. Obey company naming standards and write variable names consistently in application: e.g. txtUserName, lblUserName, cmbSchoolType, ... Otherwise readability will reduce and find/replace tools will be unusable.
  6. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. userName, UserName, USER_NAME, m_userName, username, ...
    • For example for Java, 
      • use Camel Case (aka Upper Camel Case) for classes: VelocityResponseWriter
      • use Lower Case for packages: com.company.project.ui
      • use Mixed Case (aka Lower Camel Case) for variables: studentName
      • use Upper Case for constants : MAX_PARAMETER_COUNT = 100
      • use Camel Case for enum class names and Upper Case for enum values.
      • don't use '_' anywhere except constants and enum values (which are constants).
  7. Don't reuse same variable name in the same class in different contexts: e.g. in method, constructor, class. So you can provide more simplicity for understandability and maintainability.
  8. Don't use same variable for different purposes in a method, conditional etc. Create a new and different named variable instead. This is also important for maintainability and readability.
  9. Don't use non-ASCII chars in variable names. Those may run on your platform but may not on others.
  10. Don't use too long variable names (e.g. 50 chars). Long names will bring ugly and hard-to-read code, also may not run on some compilers because of character limit.
  11. Decide and use one natural language for naming, e.g. using mixed English and German names will be inconsistent and unreadable.
  12. Use meaningful names for methods. The name must specify the exact action of the method and for most cases must start with a verb. (e.g. createPasswordHash)
  13. Obey company naming standards and write method names consistently in application: e.g. getTxtUserName(), getLblUserName(), isStudentApproved(), ... Otherwise readability will reduce and find/replace tools will be unusable.
  14. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. getUserName, GetUserName, getusername, ...
    • For example for Java, 
      • use  Mixed Case  for method names: getStudentSchoolType 
      • use  Mixed Case  for method parameters: setSchoolName(String schoolName)
  15. Use meaningful names for method parameters, so it can documentate itself in case of no documentation.

 https://www.bbc.co.uk/bitesize/guides/zb3yb82/revision/1

Variables and constants

Programs usually use data in some shape or form. Data in programs is usually referred to as values.

Variables

A variable is a named memory address that holds a value. The value held in a variable can (and usually does) change as the program is running.

A variable's name is known as an identifier. The identifer given to a variable usually follows certain rules:

  • It can contain letters and numbers but must start with a letter.
  • It must contain at least one letter (at the start of the name).
  • It must not contain special characters such as !@£$%&* or punctuation characters. However, an underscore can be used. Spaces are not allowed.
  • It should contain lowercase letters. However, uppercase letters can be used if a variable name comprises more than one word joined together.
  • The name should be meaningful - it should represent the value it is holding.
 
Acceptable identifiersUnacceptable identifiers
score Score
highScore high score
high_score 123score
highScore123 $core

Variables make it easy for a programmer to use memory locations. The computer keeps track of which memory location the variable refers to. All the programmer has to do is remember the identifier the variable was given.

Declaration and assignment

Programming languages require a variable to be identified before a value is assigned to it. This is known as declaring a variable:

score as integer - this would declare a variable called score which will hold integers.

Giving a variable a value is known as assignment. A variable must be assigned a value before it can be used. For example:

Score = 0 - this would assign the value 0 to the variable score.

Some programming languages, such as Python, enable variables to be declared and assigned a value in the same line of code.

Constants

A constant allows a value to be assigned a name. Unlike a variable, the value assigned to a constant cannot be changed whilst the programming in running.

Constants are useful because they are declared and assigned once, but can be referred to over and over again throughout the program. They are used for values that are unlikely to change, for example:

Pi - const PI = 3.142

Constants follow the same naming conventions as variables, except that they are usually in uppercase.

Global and local variables

A global variable is one that can be accessed and changed throughout the program. Usually a programmer has to declare that the variable is a global. For example:

global ID = 75

Local variables are confined to a loop or subprogram. This has the advantage of the programmer being able to use the same variable names again and again for different purposes.

When using global variables, a programmer must be careful not to use a local variable with the same name. If this happens, the value of the global variable will be changed, causing the program to produce unexpected results.

原文地址:https://www.cnblogs.com/panpanwelcome/p/15030096.html