case编程讲解(有意思的三种变量命名法)

概述

英语习惯使用空格来间隔开单词,然而这种用法在编程语言中会带来一些麻烦,所以程序员们就创造出了以下方法: 蛇形命名法(snake case) 驼峰命名法(camel case) 匈牙利命名法(HN case) 帕斯卡命名法(Pascal case) 脊柱命名法(spinal case) 自由命名法(studly caps) 驼峰蛇形命名法。

总体而言,这些命名法都是要克服单词间的空格,从而把不同单词串连起来,最终达到创造出一种新的“单词”的效果。

When it comes to naming resources in a program, there are 3 main types of case conventions: CamelCase, snake_case, and spinal-case. They are just a way of naming the resources to resemble natural language, while avoiding spaces, apostrophes and other exotic characters. This habit is universal in programming languages where only a finite set of characters is authorized for names.

不过主要常用的还是 蛇形命名法(snake case)、驼峰命名法(camel case)和 脊柱命名法(spinal case)

case编程讲解(有意思的三种变量命名法)(1)


一、驼峰命名法

CamelCase has been popularized by the Java language. It intends to emphasize the beginning of each word by making the first letter uppercase. E.g. CamelCase, CurrentUser, AddAttributeToGroup, etc. Aside from debates about its readability, its main drawback is to be ineffective in contexts which are not case sensitive.Two variants coexist:lowerCamelCase: where lowercase is used for the first letter.UpperCamelCase: where the first letter is capital.

用驼峰命名法(camel case)为变量起名字,即第一个单词首字母小写,后面单词首字母大写,例如:fileName、lineNumber。


二、蛇形命名法

snake_case has been widely used for years by C programmers, and more recently in Ruby. Words are separated by underscores “_”, thus letting a compiler or an interpreter understand it as a single symbol, but also allowing readers to separate words fluently. However, its popularity has decreased due to a lot of abuses in C programs with over-extended or too short names. Unlike camel case, there are very few contexts where snake case is not usable. Examples: snake_case, current_user, add_attribute_to_group, etc.

用蛇形命名法(snake case)为变量起名字,即用下划线将单词连接起来,例如:file_name、 line_number。


三、spinal-case

spinal-case is a variant of snake case which uses hyphens “-” to separate words. The pros and cons are quite similar to those of snake case, with the exception that some languages do not allow hyphens in symbol names (for variable, class, or function naming). You may find it referred to as lisp-case because it is the usual way to name variables and functions in lisp dialects. It is also the traditional way of naming folders and files in UNIX and Linux systems. Examples: spinal-case, current-user, add-attribute-to-group, etc.

These 3 cases have their variants, based on criteria such as first letter case, behavior with accents or other special characters. Using English is recommended, to avoid special characters.

spinal case是snake case的变体,它使用连字符“-”来分隔单词,如spinal-case, current-user, add-attribute-to-group等。


后面会分享更多devops和DBA方面内容,感兴趣的朋友可以关注下!

case编程讲解(有意思的三种变量命名法)(2)

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页