Naming convention (programming): Difference between revisions

Content deleted Content added
EmeryD (talk | contribs)
Rescuing 2 sources and tagging 0 as dead.) #IABot (v2.0.9.5
 
(568 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Set of rules for naming entities in source code and documentation}}
In [[computer programming]] a '''naming convention''' is a set of rules for choosing the character sequence to be used for an [[identifier]].
{{Use dmy dates|date=October 2020}}
In [[computer programming]], a '''naming convention''' is a set of rules for choosing the character sequence to be used for [[identifier (computer languages)|identifier]]s which denote [[Variable (computer science)|variables]], [[Data type|types]], [[Subroutine|functions]], and other entities in [[source code]] and [[Software documentation|documentation]].
 
Reasons for using a naming convention (as opposed to allowing people, eg, [[programmer]]s, to choose any character sequence) include the following:
 
* To reduce the effort needed to read and understand [[source code]];<ref>Derek M. Jones [http://www.knosof.co.uk/cbook/oprandname.pdf "Operand names influence operator precedence decisions"] An experiment investigating the effect of variable names on operator precedence selection</ref>
* to provide useful information to a reader, eg, an identifier's type (see: [[Hungarian notation]]) or its intended use
* To enable code reviews to focus on issues more important than [[Syntax (programming languages)|syntax]] and naming standards.
* to enhance clarity (for example by disallowing overly long names or abbreviations);
* To enable code quality review tools to focus their reporting mainly on significant issues other than syntax and style preferences.
 
The choice of naming conventions can be an enormouslya controversial issue, with partisans of each holding theirs to be the best and others to be inferior. Colloquially, this is said to be a matter of [[dogma]].<ref>{{cite encyclopedia |last=Raymond |first=Eric S. |author-link=Eric S. Raymond |encyclopedia=The [[Jargon File]] |title=religious issues |url=http://www.catb.org/jargon/html/R/religious-issues.html |access-date=7 November 2011 |edition=version 4.4.8 |date=1 October 2004}}</ref> Many companies have also established their own set of conventions.
 
==Potential benefits==
== Business Value of Naming Conventions ==
Benefits of a naming convention can include the following:
 
* to provide additional information (i.e., [[metadata]]) about the use to which an identifier is put;
While largely hidden from the view of most business users, "good names" when well chosen make it significantly easier for subsequent generations of analysts and developers to understand what the system is doing and how to fix or extend the [[source code]] for new business needs.
* to help formalize expectations and promote [[consistency]] within a development team;
* to enable the use of automated [[refactoring]] or search and replace tools with minimal potential for error;
* to enhance clarity in cases of potential ambiguity;
* to enhance the aesthetic and professional appearance of work product (for example, by disallowing overly long names, comical or "cute" names, or abbreviations);
* to help avoid "naming collisions" that might occur when the work product of different organizations is combined (see also: [[namespaces]]);
* to provide meaningful data to be used in project handovers which require submission of program source code and all relevant documentation;
* to provide better understanding in case of code reuse after a long interval of time.
 
==Challenges==
Example:
 
The choice of naming conventions (and the extent to which they are enforced) is often a contentious issue, with partisans holding their viewpoint to be the best and others to be inferior. Moreover, even with known and well-defined naming conventions in place, some organizations may fail to consistently adhere to them, causing inconsistency and confusion. These challenges may be exacerbated if the naming convention rules are internally inconsistent, arbitrary, difficult to remember, or otherwise perceived as more burdensome than beneficial.
a = b * c
 
==Readability==
while programmatically correct is entirely opaque as to intent or meaning.
Well-chosen identifiers make it significantly easier for developers and analysts to understand what the system is doing and how to fix or extend the [[source code]] to apply for new needs.
 
For example, although
weekly_pay = hours_worked * pay_rate
<syntaxhighlight lang="C">
a = b * c;
</syntaxhighlight>
 
is [[Syntax (programming languages)|syntactically]] correct, its purpose is not evident. Contrast this with:
is easy to read and understand (at least for programmers accustomed to such cryptic "words" and assuming you're working in a payroll application).
<syntaxhighlight lang="C">
weekly_pay = hours_worked * hourly_pay_rate;
</syntaxhighlight>
 
which implies the intent and meaning of the source code, at least to those familiar with the context of the statement.
== Multiple-word identifiers ==
 
Experiments suggest that identifier style affects recall and precision and that familiarity with a style speeds recall.<ref>{{Cite book |last1=Binkley |first1=Dave |last2=Davis |first2=Marcia |title=2009 IEEE 17th International Conference on Program Comprehension |chapter=To camelcase or under_score |date=2009 |chapter-url=http://www.cs.loyola.edu/~binkley/papers/icpc09-clouds.pdf |issue=17 |pages=158–167 |doi=10.1109/ICPC.2009.5090039|isbn=978-1-4244-3998-0 |s2cid=1450798 }}
A common recommendation is "Use meaningful identifiers." A single [[word]] may not be as sufficiently meaningful, or specific, as multiple words.
</ref>
As most [[programming language]]s do not allow the [[whitespace (computer science)|whitespace]] in identifiers, a method of delimiting each word is needed (to make it easier for subsequent readers to interpret those character sequences belonging to each word). There are several in widespread use; each with a significant following.
 
==Common elements==
One approach is to delimit separate words with a [[alphanumeric|nonalphanumeric]] character. The two characters commonly used for this purpose are the hyphen ('-') and the underscore ('_'), eg, the two-word name ''two words'' would be represented as ''two-words'' or ''two_words''. The hyphen is used by nearly all programmers writing [[Cobol]] and [[Lisp programming language|Lisp]]. Many other languages (eg, languages in the [[C programming language|C]] and [[Pascal programming language|Pascal]] families) reserve the hyphen for use as the [[subtraction]] operator, and so it is not available for use in identifiers.
{{unreferenced section|date=September 2010}}
The exact rules of a naming convention depend on the context in which they are employed. Nevertheless, there are several common elements that influence most if not all naming conventions in common use today.
 
===Length of identifiers===
An alternate approach is to indicate word boundaries using capitalization, thus rendering ''two words'' as either ''twoWords'' or ''TwoWords''. The term [[CamelCase]] (or camelCase) is sometimes used to describe this technique.
 
Fundamental elements of all naming conventions are the rules related to '''identifier length''' (i.e., the finite number of individual characters allowed in an identifier). Some rules dictate a fixed numerical bound, while others specify less precise heuristics or guidelines.
== Information in identifiers ==
 
Identifier length rules are routinely contested in practice, and subject to much debate academically.
There is significant disagreement over whether it is permissible to use short (ie, containing few characters) identifiers. One argument being that it is not possible to encode much information in a short sequence of characters. The opposition however claim that long identifiers clutter the code and obscure important syntax.
 
Some considerations:
Often forgotten in the highly personal debates over which naming practice is "best" is the fact that a typical business application will actually be written in several software languages. Every software language has its own idiosyncrasies as to special meaning characters (perhaps to indicate local vs global variable), separators, and length.
* shorter identifiers may be preferred as more expedient, because they are easier to type (although many IDEs and text-editors provide text-completion, which mitigates this)
* extremely short identifiers (such as 'i' or 'j') are very difficult to uniquely distinguish using automated search and replace tools (although this is not an issue for [[Regular expression|regex]]-based tools)
* longer identifiers may be preferred because short identifiers cannot encode enough information or appear too cryptic
* longer identifiers may be disfavored because of visual clutter
 
It is an open research issue whether some programmers prefer shorter identifiers because they are easier to type, or think up, than longer identifiers, or because in many situations a longer identifier simply clutters the visible code and provides no perceived additional benefit.
In early software languages, written on punch cards, variable names could be restricted to a maximum 6 characters. It would not be unusual for such cryptically short names (in Fortran) to be migrated to COBOL.
 
Brevity in programming could be in part attributed to:
== Extra information in identifiers ==
* early [[Linker (computing)|linkers]] which required variable names to be restricted to 6 characters to save memory. A later "advance" allowed longer variable names to be used for human comprehensibility, but where only the first few characters were significant. In some versions of [[BASIC]] such as TRS-80 Level 2 Basic, long names were allowed, but only the first two letters were significant. This feature permitted erroneous behaviour that could be difficult to debug, for example when names such as "VALUE" and "VAT" were used and intended to be distinct.
There are several well known systems for codifying specific technical aspects of a particular identifier in the name; some are listed below. Individual companies, projects and teams sometimes also devise their own such conventions.
* early [[source code editor]]s lacking [[autocomplete]]
* early low-resolution monitors with limited line length (e.g. only 80 characters)
* much of computer science originating from mathematics, where variable names are traditionally only a single letter
 
===Letter case and numerals===
* Perhaps the most well-known is [[Hungarian notation]], which encodes either the purpose ("Apps Hungarian") or the [[datatype|type]] ("Systems Hungarian") of a variable in its name[http://www.joelonsoftware.com/articles/Wrong.html].
 
Some naming conventions limit whether letters may appear in uppercase or lowercase. Other
* In [[Java programming language|Java]], very strong conventions established from the beginning by the language's originators require [[classes]] and [[variables]] to be capitalised differently. Thus, to a Java programmer, <code>widget.expand()</code> and <code>Widget.expand()</code> imply significantly different behaviour, even without prior knowledge of the <code>Widget</code> class and despite the fact that the compiler enforces no such rules.
conventions do not restrict letter case, but attach a well-defined interpretation based
on letter case. Some naming conventions specify whether alphabetic, numeric, or alphanumeric
characters may be used, and if so, in what sequence.
 
===Multiple-word identifiers===
== OF Language ==
 
A common recommendation is "Use meaningful identifiers." A single [[word]] may not be as meaningful, or specific, as multiple words. Consequently, some naming conventions specify rules for the treatment of "compound" identifiers containing more than one word.
One of the earliest published convention systems was IBM's "OF Language" documented in a 1980s IMS ([[Information Management System]]) manual. [reference to be found/supplied]
 
As most [[programming language]]s do not allow [[whitespace (computer science)|whitespace]] in identifiers, a method of delimiting each word is needed (to make it easier for subsequent readers to interpret which characters belong to which word). Historically some early languages, notably [[FORTRAN]] (1955) and [[ALGOL]] (1958), allowed spaces within identifiers, determining the end of identifiers by context. This was abandoned in later languages due to the difficulty of [[tokenization (lexical analysis)|tokenization]]. It is possible to write names by simply concatenating words, and this is sometimes used, as in <code>mypackage</code> for Java package names,<ref>[https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html Naming a Package]</ref> though legibility suffers for longer terms, so usually some form of separation is used.
While largely unheard of today (21st century), the PRIME-MODIFIER-CLASS word scheme produced highly readable (when you're a programmer and accustomed to cryptic abbreviated labels) names like this: CUST-ACT-NO (customer account number).
 
====Delimiter-separated words====
 
One approach is to [[delimiter|delimit]] separate words with a [[alphanumeric|non-alphanumeric]] character. The two characters commonly used for this purpose are the [[hyphen]] ("-") and the [[underscore]] ("_"); e.g., the two-word name "<code>two words</code>" would be represented as "<code>two-words</code>" or "<code>two_words</code>".
 
The hyphen is used by nearly all programmers writing [[COBOL]] (1959), [[Forth (programming language)|Forth]] (1970), and [[Lisp (programming language)|Lisp]] (1958); it is also common in [[Unix]] for commands and packages, and is used in [[Cascading Style Sheets|CSS]].<ref>{{cite web |title = CSS reference |website = [[Mozilla Developer Network]] |url = https://developer.mozilla.org/en-US/docs/Web/CSS/Reference |access-date=2016-06-18}}</ref> This convention has no standard name, though it may be referred to as ''lisp-case'' or ''COBOL-CASE'' (compare ''Pascal case''), ''kebab-case'', ''brochette-case'', or other variants.<ref>{{Cite web | title = StackOverflow – What's the name for snake_case with dashes? | url = https://stackoverflow.com/questions/11273282/whats-the-name-for-snake-case-with-dashes }}</ref><ref>{{Cite web | title = Programmers – If this is camelCase what-is-this? | url = http://programmers.stackexchange.com/questions/104468/if-this-is-camelcase-what-is-this | access-date = 13 August 2015 | archive-date = 7 August 2016 | archive-url = https://web.archive.org/web/20160807114459/http://programmers.stackexchange.com/questions/104468/if-this-is-camelcase-what-is-this | url-status = dead }}</ref><ref>{{Cite web | title = Camel_SNAKE-kebab | website = [[GitHub]] | url = https://github.com/qerub/camel-snake-kebab | date = September 2019 }}</ref><ref>[http://c2.com/cgi/wiki?UnderscoreVersusCapitalAndLowerCaseVariableNaming UnderscoreVersusCapitalAndLowerCaseVariableNaming]</ref> Of these, ''kebab-case'', dating at least to 2012,<ref>{{cite web |url=https://stackoverflow.com/posts/12273101/revisions |title=Revisions to jwfearn's answer to What's the name for dash-separated case? |date=5 September 2012 |author=jwfearn}}</ref> has achieved some currency since.<ref>''Living Clojure'' (2015), by Carin Meier, [https://books.google.com/books?id=b4odCAAAQBAJ&pg=PA91 p. 91]</ref><ref>[https://lodash.com/docs#kebabCase lodash: kebabCase]</ref>
 
By contrast, languages in the FORTRAN/ALGOL tradition, notably languages in the [[C (programming language)|C]] and [[Pascal (programming language)|Pascal]] families, used the hyphen for the [[subtraction]] [[infix notation|infix]] operator, and did not wish to require spaces around it (as [[free-form language]]s), preventing its use in identifiers.
 
An alternative is to use underscores; this is common in the C family (including Python), with lowercase words, being found for example in ''[[The C Programming Language]]'' (1978), and has come to be known as [[snake case]] or ''snail case''. Underscores with uppercase, as in UPPER_CASE, are commonly used for [[C preprocessor]] macros, hence known as MACRO_CASE, and for [[environment variable]]s in Unix, such as BASH_VERSION in [[bash (Unix shell)|bash]]. Sometimes this is humorously referred to as SCREAMING_SNAKE_CASE (alternatively SCREAMING_SNAIL_CASE).
 
====Letter case-separated words====
{{See also|Letter case#Special case styles}}
Another approach is to indicate word boundaries using medial capitalization, called "[[camelCase]]", "PascalCase", and many other names, thus respectively rendering "<code>two words</code>" as "<code>twoWords</code>" or "<code>TwoWords</code>". This convention is commonly used in [[Pascal (programming language)|Pascal]], [[Java (programming language)|Java]], [[C Sharp (programming language)|C#]], and [[Visual Basic]]. Treatment of initialisms in identifiers (e.g. the "[[XML]]" and "[[HTTP]]" in <code>[[XMLHttpRequest]]</code>) varies. Some dictate that they be lowercase (e.g. <code>XmlHttpRequest</code>) to ease typing, readability and ease of [[Text segmentation|segmentation]], whereas others leave them uppercased (e.g. <code>XMLHTTPRequest</code>) for accuracy.
 
====Examples of multiple-word identifier formats====
{| class="wikitable"
|+Multiple-word identifier formats
!Formatting
!Name(s)
|-
|<code>twowords</code>
|flatcase<ref name=":0">{{Cite web|title=naming - What are the different kinds of cases?|url=https://stackoverflow.com/questions/17326185/what-are-the-different-kinds-of-cases|access-date=2020-08-16|website=Stack Overflow}}</ref><ref>{{Cite web|date=2018-03-20|title=A brief list of programming naming conventions|url=https://www.deanpugh.com/a-brief-list-of-programming-naming-conventions/|access-date=2020-08-16|website=deanpugh.com|language=en-GB}}</ref>
|-
|<code>TWOWORDS</code>
|UPPERCASE, SCREAMINGCASE<ref name=":0" />
|-
|<code>twoWords</code>
|(lower) [[Camel case|camelCase]], dromedaryCase
|-
|<code>TwoWords</code>
|PascalCase, UpperCamelCase
|-
|<code>two_words</code>
|[[snake_case]], snail_case, pothole_case
|-
|<code>TWO_WORDS</code>
|ALL_CAPS, [[SCREAMING_SNAKE_CASE]],<ref>{{Cite web |title=Naming conventions |url=https://doc.rust-lang.org/1.0.0/style/style/naming/README.html |access-date=2023-05-02 |website=doc.rust-lang.org}}</ref> MACRO_CASE, CONSTANT_CASE
|-
|<code>two_Words</code>
|camel_Snake_Case
|-
|<code>Two_Words</code>
|Pascal_Snake_Case, Title_Case
|-
|<code>two-words</code>
|[[Kebab case|kebab-case]], dash-case, lisp-case, spinal-case
|-
|<code>TWO-WORDS</code>
|TRAIN-CASE, COBOL-CASE, SCREAMING-KEBAB-CASE
|-
|<code>Two-Words</code>
|Train-Case,<ref name=":0" /> HTTP-Header-Case<ref name=":1">{{Cite web|title=camel-snake-kebab|url=https://clj-commons.org/camel-snake-kebab/|access-date=2020-08-16|website=camel-snake-kebab|language=en-US}}</ref>
|}
 
==Metadata and hybrid conventions==
Some naming conventions represent rules or requirements that go beyond the requirements
of a specific project or problem ___domain, and instead reflect a greater
overarching set of principles defined by the [[software architecture]], underlying [[programming language]] or other kind of cross-project methodology.
 
===Hungarian notation===
 
Perhaps the most well-known is [[Hungarian notation]], which encodes either the purpose ("Apps Hungarian") or the [[datatype|type]] ("Systems Hungarian") of a variable in its name.<ref>{{Cite news | url=http://www.joelonsoftware.com/articles/Wrong.html |title = Making Wrong Code Look Wrong|newspaper = Joel on Software|date = 11 May 2005}}</ref> For example, the prefix "sz" for the variable szName indicates that the variable is a null-terminated string.
 
===Positional notation===
 
A style used for very short (eight characters and less) could be: LCCIIL01, where LC would be the application (Letters of Credit), C for COBOL, IIL for the particular process subset, and the 01 a sequence number.
 
This sort of convention is still in active use in mainframes dependent upon [[Job Control Language|JCL]] and is also seen in the 8.3 (maximum eight characters with period separator followed by three character file type) MS-DOS style.
 
===Composite word scheme (OF Language)===
 
IBM's "OF Language" was documented in an IMS ([[Information Management System]]) manual.
 
It detailed the PRIME-MODIFIER-CLASS word scheme, which consisted of names like "CUST-ACT-NO" to indicate "customer account number".
 
PRIME words were meant to indicate major "entities" of interest to a system.
Line 56 ⟶ 161:
MODIFIER words were used for additional refinement, qualification and readability.
 
CLASS words (in good practice)ideally would be a very short list of data types relevant to a particular application. Common CLASS words might be: NO (number), ID (identifier), TXT (text), AMT (amount), QTY (quantity), FL (flag), CD (code), W (work) and so forth. In practice, the available CLASS words would be a list of less than two dozen terms.
 
CLASS words, typically positioned on the right (suffix), serveserved much the same purpose as [[Hungarian notation]] prefixes.
 
The purpose of CLASS words, in addition to consistency, iswas to indicatespecify to the programmer the [[data type]] of data which provides clues as to what can/should be done to a particular data field. Prior to the acceptance of BOOLEAN (two values only) fields, FL (flag) would indicate a field with only two possible values.
 
==Language-specific conventions==
== Positional Notation ==
===ActionScript===
Adobe's Coding Conventions and Best Practices suggests naming standards for [[ActionScript]] that are mostly consistent with those of [[ECMAScript]].<ref>{{Cite web |title=Flex SDK coding conventions and best practices |url=https://sourceforge.net/adobe/flexsdk/wiki/Coding%20Conventions/ |website=SourceForge}}</ref> The style of identifiers is similar to that of [[JavaScript|Javascript]].
 
===Ada===
A style used for very short (8 characters and less) could be: LCCIIL01, where LC would be the application (Letters of Credit), C for COBOL, IIL for the particular process subset, and the 01 a sequence number.
In [[Ada (programming language)|Ada]], the only recommended style of identifiers is <code>Mixed_Case_With_Underscores</code>.<ref>{{Cite web|url=http://www.adaic.org/resources/add_content/docs/95style/html/sec_3/3-2-1.html|title = 3.2.1 Names - Chapter 3 - Ada 95 QUALITY AND STYLE Guide}}</ref>
 
===APL===
This sort of convention is still in active use in mainframes dependant upon [[JCL]] and is also seen in the 8.3 (maximum 8 characters with period separator followed by 3 character file type) MS-DOS style.
In [[APL (programming language)|APL]] dialects, the delta (Δ) is used between words, e.g. PERFΔSQUARE (no lowercase traditionally existed in older APL versions). If the name used underscored letters, then the delta underbar (⍙) would be used instead.
 
==External=C linksand C++===
In [[C (programming language)|C]] and [[C++]], [[keyword (computer programming)|keyword]]s and [[standard library]] identifiers are mostly lowercase. In the [[C standard library]], abbreviated names are the most common (e.g. <code>isalnum</code> for a function testing whether a character is alphanumeric), while the [[C++ standard library]] often uses an underscore as a word separator (e.g. <code>out_of_range</code>). Identifiers representing [[C preprocessor#Macro definition and expansion|macros]] are, by convention, written using only uppercase letters and underscores, for example <code>NULL</code> and <code>EINVAL</code> (this is related to the convention in many programming languages of using all-upper-case identifiers for constants). Names containing double underscore or beginning with an underscore and a capital letter are reserved for implementation ([[compiler]], [[standard library]]) and should not be used (e.g. <code>__reserved</code> or <code>_Reserved</code>).<ref>{{Cite web | title = ISO/IEC 9899:1999 Programming languages – C | publisher = ISO | url = http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=29237}}</ref><ref>{{Cite web | title = ISO/IEC 14882:2011 Information technology – Programming languages – C++ | publisher = ISO | url = http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=50372}}</ref> This is superficially similar to [[Stropping (syntax)|stropping]], but the semantics differ: the underscores are part of the value of the identifier, rather than being quoting characters (as is stropping): the value of <code>__foo</code> is <code>__foo</code> (which is reserved), not <code>foo</code> (but in a different namespace).
 
===C#===
*[http://www.wtsn.binghamton.edu/ANS/ American Name Society] Promote onomastics, the study of names and naming practices, both in the United States and abroad.
[[C Sharp (programming language)|C#]] naming conventions generally follow the guidelines published by Microsoft for all .NET languages<ref>{{Cite web | title = Naming Guidelines | date = 15 September 2021 | publisher = Microsoft | url = https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions}}</ref> (see the .NET section, below), but no conventions are enforced by the C# compiler.
*[http://www.coding-guidelines.com/cbook/sent787.pdf Coding-guidelines.com has a 100-page pdf] that uses linguistics and psychology to attempt a cost/benefit analysis of identifier naming issues
 
The Microsoft guidelines recommend the exclusive use of only <code>[[CamelCase|PascalCase]]</code> and <code>[[camelCase]]</code>, with the latter used only for method parameter names and method-local variable names (including method-local <code>const</code> values). A special exception to PascalCase is made for two-letter acronyms that begin an identifier; in these cases, both letters are capitalized (for example, <code>IOStream</code>); this is not the case for longer acronyms (for example, <code>XmlStream</code>). The guidelines further recommend that the name given to an <code>interface</code> be <code>PascalCase</code> preceded by the capital letter <code>I</code>, as in <code>IEnumerable</code>.
 
The Microsoft guidelines for naming fields are specific to <code>static</code>, <code>public</code>, and <code>protected</code> fields; fields that are not <code>static</code> and that have other accessibility levels (such as <code>internal</code> and <code>private</code>) are explicitly not covered by the guidelines.<ref>{{Cite web | title = Names of Type Members | date = 15 September 2021 | publisher = Microsoft | url = https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members}}</ref> The most common practice is to use <code>PascalCase</code> for the names of all fields, except for those which are <code>private</code> (and neither <code>const</code> nor <code>static</code>), which are given names that use <code>camelCase</code> preceded by a single underscore; for example, <code>_totalCount</code>.
 
Any identifier name may be prefixed by the commercial-at symbol (<code>@</code>), without any change in meaning. That is, both <code>factor</code> and <code>@factor</code> refer to the same object. By convention, this prefix is only used in cases when the identifier would otherwise be either a reserved keyword (such as <code>for</code> and <code>while</code>), which may not be used as an identifier without the prefix, or a contextual keyword (such as <code>from</code> and <code>where</code>), in which cases the prefix is not strictly required (at least not at its declaration; for example, although the declaration <code>dynamic&nbsp;dynamic;</code> is valid, this would typically be seen as <code>dynamic&nbsp;@dynamic;</code> to indicate to the reader immediately that the latter is a variable name).
 
===Dart/Flutter===
 
In the [[Dart_(programming_language)|Dart]] language, used in the [[Flutter_(software)|Flutter SDK]], the conventions are similar to those of Java,
except that constants are written in lowerCamelCase.
Dart imposes the syntactic rule that non-local identifiers beginning with an underscore (<code>_</code>) are treated as private
(since the language does not have explicit keywords for public or private access).
Additionally, source file names do not follow Java's "one public class per source file, name must match" rule,
instead using snake_case for filenames.<ref>{{Cite web | url=https://dart.dev/guides/language/effective-dart/style | title=Effective Dart - the Dart Style Guide}}</ref>
 
===Go===
In [[Go (programming language)|Go]], the convention is to use <code>MixedCaps</code> or <code>mixedCaps</code> rather than underscores to write multiword names. When referring to structs or functions, the first letter specifies the visibility for external packages. Making the first letter uppercase exports that piece of code, while lowercase makes it only usable within the current scope.<ref>{{Cite web | url=https://golang.org/doc/effective_go.html#mixed-caps | title=Effective Go - the Go Programming Language}}</ref>
 
===Java===
In [[Java (programming language)|Java]], naming conventions for identifiers have been established and suggested by various Java communities such as Sun Microsystems,<ref name="SunJavaCodeConv">"Code Conventions for the Java Programming Language", [http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html Section 9: "Naming Conventions"]</ref> Netscape,<ref>"NETSCAPE'S SOFTWARE CODING STANDARDS GUIDE FOR JAVA",[http://collaboratory.emsl.pnl.gov/docs/collab/sam/CodeStandards.html Collab Software Coding Standards Guide for Java] {{Webarchive|url=https://web.archive.org/web/20090303185605/http://collaboratory.emsl.pnl.gov/docs/collab/sam/CodeStandards.html |date=3 March 2009 }}</ref> AmbySoft,<ref>[http://www.ambysoft.com/essays/javaCodingStandards.html "AmbySoft Inc. Coding Standards for Java v17.01d"]</ref> etc. A sample of naming conventions set by Sun Microsystems are listed below,
where a name in "[[CamelCase]]" is one composed of a number of words joined without spaces, with each word's -- excluding the first word's -- initial letter in capitals – for example "camelCase".
{| class="wikitable" border="1"
|-
! Identifier type
! Rules for naming
! Examples
|-
| Classes
| Class names should be nouns in <code>Upper[[CamelCase]]</code>, with the first letter of every word capitalised. Use whole words – avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
|
* <code>class Raster {}</code>
* <code>class ImageSprite {}</code>
|-
| Methods
| Methods should be verbs in <code>lower[[CamelCase]]</code> or a multi-word name that begins with a verb in lowercase; that is, with the first letter lowercase and the first letters of subsequent words in uppercase.
|
* <code>run();</code>
* <code>runFast();</code>
* <code>getBackground();</code>
|-
|Variables
|Local variables, instance variables, and class variables are also written in <code>lower[[CamelCase]]</code>. Variable names should not start with underscore (<code>_</code>) or dollar sign (<code>$</code>) characters, even though both are allowed. This is in contrast to other [[coding conventions]] that state that underscores should be used to prefix all instance variables.
 
Variable names should be short yet meaningful. The choice of a variable name should be [[mnemonic]] — that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
|
* <code>int i;</code>
* <code>char c;</code>
* <code>float myWidth;</code>
|-
|Constants
|Constants should be written in [[Snake case|SCREAMING_SNAKE_CASE]]. Constant names may also contain digits if appropriate, but not as the first character.
|
* {{code|2=java|1=static final int MAX_PARTICIPANTS = 10;}}
|}
Java compilers do not enforce these rules, but failing to follow them may result in confusion and erroneous code. For example, <code>widget.expand()</code> and <code>Widget.expand()</code> imply significantly different behaviours: <code>widget.expand()</code> implies an invocation to method <code>expand()</code> in an instance named <code>widget</code>, whereas <code>Widget.expand()</code> implies an invocation to static method <code>expand()</code> in class <code>Widget</code>.
 
<!-- The stuff below was removed from the [[CamelCase]] article - needs merging with the above -->
One widely used Java coding style dictates that <code>[[CamelCase|UpperCamelCase]]</code> be used for [[class (computer science)|classes]] and <code>[[CamelCase|lowerCamelCase]]</code> be used for [[instance (computer science)|instances]] and [[method (computer science)|methods]].<ref name="SunJavaCodeConv" />
Recognising this usage, some [[Integrated development environment|IDEs]], such as [[Eclipse (IDE)|Eclipse]], implement shortcuts based on CamelCase. For instance, in Eclipse's [[content assist]] feature, typing just the upper-case letters of a CamelCase word will suggest any matching class or method name (for example, typing "NPE" and activating content assist could suggest <code>NullPointerException</code>).
 
Initialisms of three or more letters are CamelCase instead of uppercase (e.g., <code>parseDbmXmlFromIPAddress</code> instead of <code>parseDBMXMLFromIPAddress</code>). One may also set the boundary at two or more letters (e.g. <code>parseDbmXmlFromIpAddress</code>).
 
===JavaScript===
 
The built-in JavaScript libraries use the same naming conventions as Java. Data types and constructor functions use upper camel case (<code>RegExp</code>, <code>TypeError</code>, <code>XMLHttpRequest</code>, <code>DOMObject</code>) and methods use lower camel case (<code>getElementById</code>, <code>getElementsByTagNameNS</code>, <code>createCDATASection</code>). In order to be consistent most JavaScript developers follow these conventions.<ref>{{cite web|url=https://codeburst.io/5-javascript-style-guides-including-airbnb-github-google-88cbc6b2b7aa|title=5 JavaScript Style Guides – Including AirBnB, GitHub, & Google|last1=Morelli|first1=Brandon|date=17 November 2017|website=codeburst.io|access-date=17 August 2018}}</ref>
See also: [https://www.crockford.com/code.html Douglas Crockford's conventions]
 
===Lisp===
Common practice in most [[Lisp (programming language)|Lisp]] dialects is to use dashes to separate words in identifiers, as in <code>with-open-file</code> and <code>make-hash-table</code>. Dynamic variable names conventionally start and end with asterisks: <code>*map-walls*</code>. Constants names are marked by plus signs: <code>+map-size+</code>.<ref>{{Cite web | url=http://www.gigamonkeys.com/book/variables.html |title = Variables}}</ref><ref>[http://www.cliki.net/Naming+conventions Naming conventions] on [[CLiki]]</ref>
 
===.NET===
[[Microsoft .NET]] recommends <code>[[CamelCase|UpperCamelCase]]</code>, also known as ''PascalCase'', for most identifiers. (<code>[[CamelCase|lowerCamelCase]]</code> is recommended for [[parameter (computer science)|parameters]] and [[variable (programming)|variables]]) and is a shared convention for the .NET languages.<ref>[http://msdn.microsoft.com/en-us/library/ms229043.aspx Microsoft .NET Framework Capitalization Styles]</ref> Microsoft further recommends that no type prefix hints (also known as [[Hungarian notation]]) are used.<ref>[http://msdn.microsoft.com/en-us/library/ms229045.aspx .NET Framework Developer's Guide – General Naming Conventions]</ref> Instead of using Hungarian notation it is recommended to end the name with the base class' name; <code>LoginButton</code> instead of <code>BtnLogin</code>.<ref>[Framework Design Guidelines, Krzysztof Cwalina, Brad Abrams Page 62]</ref>
 
===Objective-C===
[[Objective-C]] has a common coding style that has its roots in [[Smalltalk]] .
 
Top-level entities, including classes, protocols, categories, as well as C constructs that are used in Objective-C programs like global variables and functions, are in UpperCamelCase with a short all-uppercase prefix denoting namespace, like <code>NSString</code>, <code>UIAppDelegate</code>, <code>NSApp</code> or <code>CGRectMake</code>. Constants may optionally be prefixed with a lowercase letter "k" like <code>kCFBooleanTrue</code>.
 
Instance variables of an object use lowerCamelCase prefixed with an underscore, like <code>_delegate</code> and <code>_tableView</code>.
 
Method names use multiple lowerCamelCase parts separated by colons that delimit arguments, like: <code>application:didFinishLaunchingWithOptions:</code>, <code>stringWithFormat:</code> and <code>isRunning</code>.
 
===Pascal, Modula-2 and Oberon===
Wirthian languages Pascal, Modula-2 and Oberon generally use <code>Capitalized</code> or <code>UpperCamelCase</code> identifiers for programs, modules, constants, types and procedures, and <code>lowercase</code> or <code>lowerCamelCase</code> identifiers for math constants, variables, formal parameters and functions.<ref>[https://web.archive.org/web/20161008155209/http://modula-2.info/m2r10/pmwiki.php/Recommendations/NameConvention#Identifiers Modula-2 Name Convention]</ref> While some dialects support underscore and dollar signs in identifiers, snake case and macro case is more likely confined to use within foreign API interfaces.<ref>{{Cite web |url=http://modula-2.info/m2r10/pmwiki.php/Recommendations/NameConvention#ForeignAPIIdentifiers |title=Foreign API Identifiers in Modula-2 Name Convention |access-date=15 June 2016 |archive-date=10 September 2016 |archive-url=https://web.archive.org/web/20160910004620/http://modula-2.info/m2r10/pmwiki.php/Recommendations/NameConvention/#ForeignAPIIdentifiers |url-status=dead }}</ref>
 
===Perl===
[[Perl]] takes some cues from its C heritage for conventions. Locally scoped variables and subroutine names are lowercase with infix underscores. Subroutines and variables meant to be treated as private are prefixed with an underscore. Package variables are title cased. Declared constants are all caps. Package names are camel case excepting pragmata—e.g., <code>strict</code> and <code>mro</code>—which are lowercase.
<ref>{{Cite web | title = Perl style guide | url = http://perldoc.perl.org/perlstyle.html }}</ref>
<ref>{{Cite web | title = perlmodlib – constructing new Perl modules and finding existing ones | url = http://perldoc.perl.org/perlmodlib.html }}</ref>
 
===PHP===
[[PHP]] recommendations are contained in PSR-1 ([[PHP Standard Recommendation]] 1) and PSR-12.<ref name=PSR>{{Cite web | title = PHP standards recommendations | url = http://www.php-fig.org/psr/}}</ref> According to PSR-1, class names should be in PascalCase, class constants should be in MACRO_CASE, and function and method names should be in camelCase.<ref>{{Cite web|url=https://www.php-fig.org/psr/psr-1/|title = PSR-1: Basic Coding Standard - PHP-FIG}}</ref>
 
=== Python and Ruby ===
[[Python (programming language)|Python]] and [[Ruby (programming language)|Ruby]] both recommend <code>UpperCamelCase</code> for class names, <code>CAPITALIZED_WITH_UNDERSCORES</code> for constants, and <code>snake_case</code> for other names.
 
In Python, if a name is intended to be "[[private member|private]]", it is prefixed by one or two underscores. Private variables are enforced in Python only by convention. Names can also be suffixed with an underscore to prevent conflict with Python keywords. Prefixing with double underscores changes behaviour in classes with regard to [[name mangling#Python|name mangling]]. Prefixing ''and'' suffixing with double underscores - the so-called "dunder" ("double under") methods in Python - are reserved for "magic names" which fulfill special behaviour in Python objects.<ref name=pep8>[https://www.python.org/dev/peps/pep-0008/ Style Guide for Python Code PEP8]</ref>
 
=== R ===
While there is no official style guide for [[R (programming language)|R]], the [[tidyverse]] style guide from R-guru Hadley Wickham sets the standard for most users.<ref name=tidyverse>[https://style.tidyverse.org/ Style Guide for RCode ]</ref> This guide recommends using only numbers, lowercase letters and underscores for file, variable and function names e.g. fit_models.R. The Bioconductor style guide recommends UpperCamelCase for class names and lowerCamelCase for variable and function names.
 
Its predecessors S and S-PLUS did not allow underscores in variable and function names, but instead used the period as a delimiter. As a result, many base functions in R still have a period as delimiter e.g. as.data.frame().
 
Hidden objects can be created with the dot prefix e.g. .hidden_object. These objects do not appear in the global environment. The dot prefix is often used by package developers for functions that are purely internal and are not supposed to be used by end users. It is similar to the underscore prefix in Python.
 
===Raku===
[[Raku (programming language)|Raku]] follows more or less the same conventions as Perl, except that it allows an infix hyphen <code>-</code> or an apostrophe <code>'</code> (or single quote) within an identifier (but not two in a row), provided that it is followed by an alphabetic character. Raku programmers thus often use ''kebab case'' in their identifiers; for example,
<code>fish-food</code> and <code>don't-do-that</code> are valid identifiers.
<ref>{{Cite web | title = General rules of Perl 6 syntax | url = https://docs.perl6.org/language/syntax#Identifiers }}</ref>
 
=== Rust ===
[[Rust (programming language)|Rust]] recommends <code>UpperCamelCase</code> for type aliases and struct, trait, enum, and enum variant names, <code>SCREAMING_SNAKE_CASE</code> for constants or statics and <code>snake_case</code> for variable, function and struct member names.<ref>{{Cite web|url=https://doc.rust-lang.org/1.0.0/style/style/naming/README.html|title=Naming conventions|website=doc.rust-lang.org|language=en|access-date=2018-02-04}}</ref>
 
===Swift===
[[Swift (programming language)|Swift]] has shifted its naming conventions with each individual release. However a major update with Swift 3.0 stabilised the naming conventions for <code>lowerCamelCase</code> across variables and function declarations. Constants are usually defined by enum types or constant parameters that are also written this way. Class and other object type declarations are <code>UpperCamelCase</code>.
 
As of Swift 3.0 there have been made clear naming guidelines for the language in an effort to standardise the API naming and declaration conventions across all third party APIs.
<ref>{{Cite web | title = swift.org API Design Guidelines | url = http://swift.org/documentation/api-design-guidelines/#conventions }}</ref>
 
==See also==
*[[:Category:Naming conventions]]
*[[Checkstyle]]
*[[Coding conventions]]
*[[List of tools for static code analysis]]
*[[Namespace]]
*[[Naming convention]]
*[[Sigil (computer programming)]]
*[[Syntax (programming languages)]]
 
==References==
{{Reflist}}
 
==External links==
*[http://www.coding-guidelines.com/cbook/sent792.pdf coding-guidelines.com has a pdf] that uses linguistics and psychology to attempt a cost/benefit analysis of identifier naming issues
 
[[Category:Source code]]
[[Category:namingNaming conventions| Programming]]