Naming conventions: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 49:
;In the Formal Specification
The revised report used "shorthand" to indicate an MODE was "private" to the language specification. The character ℒ was used to indicate that the name could be repeated for every precision... e.g. ℒ INT could mean: ... SHORT SHORT INT, SHORT INT, INT, LONG INT, LONG LONG INT etc and ℓ cos could mean: short short cos, short cos, cos, long cos, long long cos etc.
<langsyntaxhighlight lang="algol68">MODE ℵ SIMPLEOUT = UNION (≮ℒ INT≯, ≮ℒ REAL≯, ≮ℒ COMPL≯, BOOL, ≮ℒ BITS≯, CHAR, [ ] CHAR);
PROC ℓ cos = (ℒ REAL x) ℒ REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;
 
Line 55:
 
PROC ℓ arccos = (ℒ REAL x) ℒ REAL: ¢ if ABS x ≤ ℒ 1, a ℒ real value close
to the inverse cosine of 'x', ℒ 0 ≤ ℒ arccos (x) ≤ ℒ pi ¢; </langsyntaxhighlight>
For LONG LONG MODEs this would be coded as:
<langsyntaxhighlight lang="algol68">PROC long long cos = (LONG LONG REAL x) LONG LONG REAL: ¢ a ℒ real value close to the cosine of 'x' ¢;
 
PROC long long complex cos = (LONG LONG COMPL z) LONG LONG COMPL: ¢ a ℒ complex value close to the cosine of 'z' ¢;
 
PROC long long arccos = (LONG LONG REAL x) LONG LONG REAL: ¢ if ABS x ≤ ℒ 1, a ℒ real value close
to the inverse cosine of 'x', ℒ 0 ≤ ℒ arccos (x) ≤ ℒ pi ¢; </langsyntaxhighlight>
Note: The type returned by the '''proc'''edure is generally prefixed to the '''proc'''edure name.
 
Line 84:
'''od'''
|| Quote stropping<br/>(like [[wp:Lightweight markup language#Text/font-face formatting|wikitext]])
<langsyntaxhighlight lang="algol68">
'pr' quote 'pr'
'mode' 'xint' = 'int';
Line 93:
sum sq+:=i↑2
'od'
</syntaxhighlight>
</lang>
|| For a [[wp:List of binary codes#Seven-bit binary codes|7-bit]] character code compiler
<langsyntaxhighlight lang="algol68">
.PR UPPER .PR
MODE XINT = INT;
Line 104:
sum sq+:=i**2
OD
</syntaxhighlight>
</lang>
|| For a [[wp:Six-bit character code|6-bit]] character code compiler
<langsyntaxhighlight lang="algol68">
.PR POINT .PR
.MODE .XINT = .INT;
Line 115:
SUM SQ .PLUSAB I .UP 2
.OD
</syntaxhighlight>
</lang>
|| Algol68 using '''res''' stropping<br/>(reserved word)
<langsyntaxhighlight lang="algol68">
.PR RES .PR
mode .xint = int;
Line 126:
sum sq+:=i↑2
od
</syntaxhighlight>
</lang>
|}
Note that spaces are permitted in constants, variable and '''proc'''edure names.
Line 200:
 
=={{header|AntLang}}==
<langsyntaxhighlight AntLanglang="antlang">variables-are-often-lower-case-and-seperated-like-this-one</langsyntaxhighlight>
 
=={{header|Arturo}}==
Line 214:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# Field names begin with $ so $1 is the first field, $2 the second and $NF the
# last. $0 references the entire input record.
Line 261:
# special files:
# /dev/stdin /dev/stdout /dev/error
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 274:
 
The names of user-defined functions (which return exactly one value) and procedures (which may have no return value, or one, or several) must begin with <tt>FN</tt> or <tt>PROC</tt>, respectively. Many users find it convenient to follow this prefix with an underscore—so a procedure that takes a float, an array of strings, and an integer and then returns two integers might be defined as follows:
<langsyntaxhighlight lang="bbcbasic">DEF PROC_foo(bar, baz$(), quux%, RETURN fred%, RETURN jim%)</langsyntaxhighlight>
Names like <tt>PROCfoo</tt> and <tt>FNbar</tt> are sometimes used, and even <tt>PROCFOO</tt> and <tt>FNBAR</tt> are entirely legal; but they are probably less readable.
 
Line 288:
 
;Libraries
Constants that appear in C "header" files are typically in upper-case: <langsyntaxhighlight lang="c">O_RDONLY, O_WRONLY, or O_RDWR. O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC</langsyntaxhighlight>
Note also that there are remnants of some historic naming conventions in C where constants were required to be 8 characters or less. The "O_CREAT" constant is an example.
 
Types are often suffixed with a "_t", e.g. size_t, and "private" types and arguments are prefixed with "__":
<langsyntaxhighlight lang="c">extern size_t fwrite (__const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __s) __wur;</langsyntaxhighlight>
However there are some instances where types use all upper-case. The classic is the type FILE.
 
In C, the standard library for floating point is focused on double precision, hence the function "cos" is for double precision, and a suffix of "f" and "l" indicate single precision and quad precision respectively.
<langsyntaxhighlight lang="c">#include <math.h>
double cos(double x);
float cosf(float x);
long double cosl(long double x);</langsyntaxhighlight>
 
Whereas for complex variable a prefix of "c" is added.
<langsyntaxhighlight lang="c">#include <complex.h>
double complex ccos(double complex z);
float complex ccosf(float complex z);
long double complex ccosl(long double complex z);</langsyntaxhighlight>
 
This prefix/suffix convention extends to other standard c library function, for example in the following the "f" suffix indicates that an argument is a format string, the prefixes of "s", "v" and "n" hint at other argument types:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int printf(const char *format, ...);
Line 321:
int vfprintf(FILE *stream, const char *format, va_list ap);
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);</langsyntaxhighlight>
 
;Function names
Line 342:
'''Naming'''<br/>
- Names of enums should be plural if it's a flags enum, otherwise it should be singular.
<langsyntaxhighlight lang="csharp">public enum Planet {
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Line 358:
Workdays = Monday | Tuesday | Wednesday | Thursday | Friday
AllWeek = Sunday | Saturday | Workdays
}</langsyntaxhighlight>
You should:<br/>
- prefix interface names with I e.g. IPrinter
- prefix generic type parameters with T e.g. <syntaxhighlight lang ="csharp">Dictionary<TKey, TValue></langsyntaxhighlight>
most of the time, a single T is sufficient e.g. <syntaxhighlight lang ="csharp">IPrinter<T></langsyntaxhighlight>
- postfix type names that inherit from EventArgs, Exception, Attribute and EventHandler e.g. MouseMoveEventArgs<br/>
- postfix async method names with Async e.g. GetDataAsync()
Line 414:
* Type names for errors or warnings usually explicitly have the word “warning” or “error” in the name, eg, <code>Server-Unreachable-Error</code>
 
* Macros that establish a dynamic state and clean up after it are usually named <code>With-</code>some-context; eg, <code>With-Open-File</code>, <code>With-Database-Connection</code>. Usually, such a macro will take a first argument as a list like a normal function call, followed by <code>&body</code>, mimicking <code>With-Open-File</code> and the like. <langsyntaxhighlight lang="lisp">
(defvar *language* :en
"The language to use for messages (defaults to English)")
Line 449:
Hace demasiado frío en invierno
It's too cold in winter
</syntaxhighlight>
</lang>
 
* Function names ending in a <code>*</code> are minor variants of the same-named function without the star; eg, the standard <code>Let</code> and <code>Let*</code> special forms.
 
* Keywords for keyword arguments tend to follow the names used in standard library functions when possible, or mimic the patterns of them. “Private” arguments that callers probably won't need/want to set are usually given non-keyword symbols as their names; eg <langsyntaxhighlight lang="lisp">
(defun do-something (argument &key ((secret-arg secret) "default"))
(format t "Argument is ~a, secret is ~a" argument secret))
Line 461:
;; Special caller:
(do-something "Foo" 'secret-arg "Bar")
</syntaxhighlight>
</lang>
 
* Functions which operate on a subset selected by a predicate function usually have names ending in <code>-If</code> or <code>-If-Not</code>; eg, <code>Remove-If-Not</code>
Line 473:
** Coërcion or conversion functions that explicitly change something from type “a” to type “b” are usually named one of these patterns: <code>a->b</code>, <code>b<-a</code>, <code>b-from-a</code>, or <code>a-b</code>. The last form, with just a hyphen, mimics the standard functions <code>code-char</code> and <code>char-code</code>, but is a bit more ambiguous.
 
* The name <code>_</code> (and sometimes names like <code>__</code> or <code>_2</code> are sometimes used to indicate ignored values for which a more meaningful name isn't available; for example, skipping an always-blank field in input records. There's nothing “magical” about the name, though; you still need to <code>(declare (ignore _))</code>, so using a more meaningful name is usually preferred. <code>_</code> is most often used for <code>&rest</code> arguments. <langsyntaxhighlight lang="lisp">
#+sbcl
(defun user-name+home-phone (user-id)
Line 483:
(declare (ignore office office-phone _))
(values real-name home-phone)))
</syntaxhighlight>
</lang>
 
* Argument names are usually self-documenting; since most IDE's will show the argument names in some way (eg: Emacs shows them in the mode line after a function name is entered), using a name like <code>message</code> rather than <code>m</code> (for example) will make the usage clearer. Functions with more than 2 arguments will usually have many/most arguments as keyword arguments.
Line 503:
Dyalect keywords, variables, constants and functions should be written using <code>camelCase</code>. This stays true for the module names. Type names, constructors and methods however use <code>PascalCase</code>:
 
<langsyntaxhighlight lang="dyalect">var xs = Array.Empty(10)
var ys = Array(1, 2, 3)
var str = xs.ToString()
 
type Maybe = Some(x) or None()
var x = Maybe.Some(42)</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 649:
====Fetch and Store====
Forth has a WORD to fetch an integer from a memory address called '@' and another WORD to store an integer to memory called '!'. There are also WORDs to fetch and store double integers called 2@ and 2!. This is the beginning of a common naming convention in Forth. The '@' and '!' characters are used as suffixes for WORDs that get or put data.
<syntaxhighlight lang="text">\ fetch and store usage examples
VARIABLE MYINT1
VARIABLE MYINT2
Line 665:
 
HR_RECORD 992 PERSONEL RECORD! \ store HR_RECORD
</syntaxhighlight>
</lang>
 
====Colon, Semi-colon====
The Forth compiler is activated with ":" which is just another WORD to Forth. The colon WORD accepts the name of a new word and then begins compiling the WORDs that come after until the WORD ';' is encountered in the input stream. For this reason these two characters are sometimes used in naming WORDS that create new words or for example in Object orient extensions to Forth.
<syntaxhighlight lang="text">\ buffer is a word that creates a named memory space and ends in a ':'
: buffer: ( bytes -- ) create allot ;
hex 100 buffer: mybuffer \ buffer: creates a new WORD in the dictionary call mybuff
Line 679:
m: clear 0 swap ! ;m
;class
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
===From the beginning===
The name of every Fortran variable must start with a letter and continues with letters and digits only. A variable has an implicit type determined by the first letter of the variable's name. The implicit types are as follows:<langsyntaxhighlight lang="fortran">IMPLICIT REAL(A-H,O-Z), INTEGER(I-M)</langsyntaxhighlight>
First Fortran (1957, for the IBM704) provided no type declarations, so all variables had to be named according to the fixed implicit typing rule, further, no name could be the same as that of a library function after its terminating F was removed. Thus, SINF was for the sine function and so SIN was not an available name for a variable. Similarly, fixed-point (i.e. integer) functions had to start with X despite the rule for variables. The DIMENSION statement defined the sizes of arrays but there was no requirement on the form of the name, for instance that the first letter be an A or similar. Typically, loop variables and array indices are one of I, J, K, L, M, N but there is no requirement enforcing this, other than the integer type rule.
 
Line 699:
===A persistent problem===
Rather than evoking an "undeclared" error message any misspelled variables will be implicitly declared. Typographic mistakes may result in syntactically correct but semantically wrong statements involving such undeclared names, especially given that Fortran disregards spaces outside text literals so that <code>GO TO</code> is just as valid as <code>G OTO</code>. Such errors are very difficult to perceive in source listings. For example the output from the following snippet isn't all the integers from 1 to 10:
<langsyntaxhighlight lang="fortran"> DO 999 I=1 10
PRINT *,I
999 CONTINUE</langsyntaxhighlight>
 
Notoriously, the U.S.A.'s first Venus satellite probe was lost due to the difference between <code>DO 3 I = 1.3</code> and <code>DO 3 I = 1,3</code> Such texts when printed in wobbly glyphs through a coarse ink ribbon onto rough paper by a lineprinter in a hurry are not obviously incorrect...
 
;Quirky response
In Fortran 77 then <syntaxhighlight lang ="fortran">IMPLICIT NONE</langsyntaxhighlight> was available to disable implicit typing and thus evoke "undeclared variable" messages. Prior to this the code could use
<syntaxhighlight lang ="fortran">IMPLICIT LOGICAL</langsyntaxhighlight> in the hope that the compiler would detect an undeclared LOGICAL variable used in a numerical context, and hence report a semantic type error.
 
=={{header|Free Pascal}}==
Line 800:
 
The following program illustrates these conventions:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
const val SOLAR_DIAMETER = 864938
Line 830:
println("\nIts planetary system comprises : ")
ss.listPlanets()
}</langsyntaxhighlight>
 
{{out}}
Line 841:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
Naming conventions
 
Line 883:
- an alternative could be to prefix and postfix names, say :a: and :a1: which have a null intersection.
It's a matter of choice let to the coder. In all cases naming must be done with the utmost care.
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Line 894:
- Use _ for unneeded variables
- Don't use Hungarian Notation
<langsyntaxhighlight Lualang="lua">local DISTANCE_MAXIMUM = 1
local distance_to_target = 0
local function distanceToTarget() end
Line 901:
for _,v in ipairs(table) do
print(v)
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 918:
 
Groups which return strings also have to use $ in names, but these have two names as in this example:
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Class Alfa$ {
Private:
Line 953:
Checkit &A$
Print A$
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Line 972:
:- Type identifiers should be in PascalCase. All other identifiers should be in camelCase with the exception of constants which may use PascalCase but are not required to.
 
<langsyntaxhighlight Nimlang="nim"># Constants can start with either a lower case or upper case letter.
const aConstant = 42
const FooBar = 4.2
Line 980:
# Types must start with an uppercase letter.
type
FooBar = object</langsyntaxhighlight>
 
:- When naming types that come in value, pointer, and reference varieties, use a regular name for the variety that is to be used the most, and add a "Obj", "Ref", or "Ptr" suffix for the other varieties. If there is no single variety that will be used the most, add the suffixes to the pointer variants only.
Line 988:
:- Unless marked with the {.pure.} pragma, members of enums should have an identifying prefix, such as an abbreviation of the enum's name.
 
<langsyntaxhighlight Nimlang="nim">type
PathComponent = enum
pcDir
pcLinkToDir
pcFile
pcLinkToFile</langsyntaxhighlight>
 
:- Non-pure enum values should use camelCase whereas pure enum values should use PascalCase.
 
<langsyntaxhighlight Nimlang="nim">type
PathComponent {.pure.} = enum
Dir
LinkToDir
File
LinkToFile</langsyntaxhighlight>
 
=={{header|OASYS Assembler}}==
Line 1,144:
The convention is to use full English lowercase words separated by dashes
 
<langsyntaxhighlight Racketlang="racket">#lang racket
render-game-state
send-message-to-client
traverse-forest</langsyntaxhighlight>
 
Usually <code>_</code> is used only as the name of a dummy argument.
Line 1,153:
Most functions names have as prefix the data type of the main argument. Some notable exceptions are the functions for <code>list</code>s and <code>box</code>es, for backward compatibility.
 
<langsyntaxhighlight Racketlang="racket">#lang racket
(string-ref "1234" 2)
(string-length "123")
Line 1,159:
;exceptions:
(append (list 1 2) (list 3 4))
(unbox (box 7))</langsyntaxhighlight>
 
This convention generalizes the selector-style naming scheme of <code>struct</code>s.
 
<langsyntaxhighlight Racketlang="racket">#lang racket
(struct pair (x y) #:transparent #:mutable)
(define p (pair 1 2))
Line 1,169:
(set-pair-y! p 3)
p ; ==> (pair 1 3)
</syntaxhighlight>
</lang>
 
The name of conversion procedure is usually like <code>from-&gt;to</code>
<langsyntaxhighlight Racketlang="racket">#lang racket
(list->vector '(1 2 3 4))
(number->string 7)</langsyntaxhighlight>
 
In addition to regular alphanumeric characters, some special characters are used by convention to indicate something about the name. The more usual are:
 
<syntaxhighlight lang="racket">
<lang Racket>
;predicates and boolean-valued functions: ?
(boolean? 5)
Line 1,193:
;interfaces: <%>;
dc<%>;
font-name-directory<%></langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,269:
 
For example:
<langsyntaxhighlight lang="rexx">w=length(abc)</langsyntaxhighlight>
─── where &nbsp; '''length''' &nbsp; is a REXX BIF for the &nbsp; ''length'' &nbsp; of the &nbsp; value &nbsp; of the variable &nbsp; '''ABC'''
 
If there is an internal function with a built-in function's name in the program, &nbsp; the built-in (REXX)
<br>function can be invoked using its name as an uppercase literal string as shown below:
<langsyntaxhighlight lang="rexx">s= 'abcd'
say "length(s) =" length(s) /* ──► 1000 */
say "'LENGTH'(s) =" 'LENGTH'(s) /* ──► 4 */
exit
 
length: return 1000</langsyntaxhighlight>
{{out|output}}
<pre>
Line 1,318:
===Method names===
Method names in ruby are quite similar to variable naming conventions with a few additional rules. In ruby, a method that returns a boolean traditionally ends with a question mark. Many of these methods exist in the standard library such as, <code>1.positive?</code> or <code>'test'.tainted?</code>. Also, so called <i>destructive</i> methods end with an exclamation point. For example,
<syntaxhighlight lang="ruby">
<lang Ruby>
test_variable = [1, 9, 8, 3]
test_variable.sort # => [1, 3, 8, 9]
Line 1,324:
test_variable.sort! # => [1, 3, 8, 9]
test_variable # => [1, 3, 8, 9]
</syntaxhighlight>
</lang>
The <code>sort</code> method just returns a sorted version of the array, but the <code>sort!</code> method sorts the array in place. Additionally, Ruby has accessors in its class so you don't need to write explicit getters or setters, but if you do the proper naming convention for a getter is <code>field_name</code> and the proper naming convention for a setter is <code>field_name=</code>. An example of this will be seen later on in this description. Constructors are always named <code>initialize</code>.
 
Line 1,333:
Here is an example of a ruby file with proper naming conventions being used.
 
<syntaxhighlight lang="ruby">
<lang Ruby>
# Global variable
$number_of_continents = 7
Line 1,381:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Line 1,425:
'''Camel case:'''<br>
The variable name begins with a prefix and has one or more uppercase inside.
<syntaxhighlight lang ="vb">Dim dblDistance as Double</langsyntaxhighlight>
'''Hungarian notation:'''
<langsyntaxhighlight lang="vb">Dim iRow as Integer, iColumn as Integer
Dim sName as String
Dim nPopulation as Long
Dim xLightYear as Double
iRow = iRow + 1</langsyntaxhighlight>
Prefix i is for index and n for count. The Hungarian notation reminds in a way FORTRAN implicit type: prefix characters i,j,k,l,m,n for integers and the rest for reals.<br>
The real advantage is for the names of the VB controls.
Line 1,473:
|}
Exemple:
<langsyntaxhighlight lang="vb">txtTraduc.Width = iWidth
cmdSolution.Enabled = False
mnuAleatoire.Checked = False
frmScore.Show vbModal
picFace.Visible = False
picFace.Picture = LoadPicture(sFileName)</langsyntaxhighlight>
The advantage comes clear for the “Private Sub” names of the controls:
<langsyntaxhighlight lang="vb">mnuQuit_Click()
cmdSolution_Click()
frmScore_Resize()</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 1,564:
 
;Examples:
<syntaxhighlight lang="zig">
<lang Zig>
const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
Line 1,608:
// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}
</syntaxhighlight>
</lang>
These are general rules of thumb; if it makes sense to do something different, do what makes sense. For example, if there is an established convention such as <code>ENOENT</code>, follow the established convention.
 
10,327

edits