Naming conventions: Difference between revisions
m
Reformatting text which was overflowing the page width.
Puppydrum64 (talk | contribs) |
m (Reformatting text which was overflowing the page width.) |
||
(12 intermediate revisions by 7 users not shown) | |||
Line 44:
* A subroutine called by a macro will often be the macro's name with "do" in front. For example, if a macro is named "getScreenPosition" the associated subroutine is called "doGetScreenPosition" (note that the G in Get is now capitalized since it's no longer the beginning of the name.)
* <code>byte</code> is 8-bit and <code>word</code> is 16-bit. Strings, pointers, and other data still use either of these declarations depending on what is appropriate. It is up to the program to interpret this data "correctly" - the CPU does not enforce data types whatsoever.
=={{header|ALGOL 68}}==
;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.
<
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 ¢; </
For LONG LONG MODEs this would be coded as:
<
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 ¢; </
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]])
<
'pr' quote 'pr'
'mode' 'xint' = 'int';
Line 93:
sum sq+:=i↑2
'od'
</syntaxhighlight>
|| For a [[wp:List of binary codes#Seven-bit binary codes|7-bit]] character code compiler
<
.PR UPPER .PR
MODE XINT = INT;
Line 104:
sum sq+:=i**2
OD
</syntaxhighlight>
|| For a [[wp:Six-bit character code|6-bit]] character code compiler
<
.PR POINT .PR
.MODE .XINT = .INT;
Line 115:
SUM SQ .PLUSAB I .UP 2
.OD
</syntaxhighlight>
|| Algol68 using '''res''' stropping<br/>(reserved word)
<
.PR RES .PR
mode .xint = int;
Line 126:
sum sq+:=i↑2
od
</syntaxhighlight>
|}
Note that spaces are permitted in constants, variable and '''proc'''edure names.
Line 200:
=={{header|AntLang}}==
<
=={{header|Arturo}}==
Line 214:
=={{header|AWK}}==
<syntaxhighlight 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>
=={{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:
<
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 282:
If the first line of the program is a comment line of the form <tt>REM >myprog</tt>, the <tt>SAVE</tt> command can be used with no filename and the program will be saved as (in this case) <tt>myprog</tt>. Otherwise, it would be necessary to use <tt>SAVE "myprog"</tt>.
=={{header|BQN}}==
BQN uses a context-free grammar, a result of which it has explicit naming conventions defined in its interpreter. The basic types of values can be distinguished by their first and last characters as follows:
<syntaxhighlight lang="bqn"># Subjects (arrays, numbers, characters, etc) start with a lowercase letter:
var←3
arr←⟨1,2⟩
# Functions start with an uppercase letter:
Fun←{𝕨+𝕩}
Avg←+´÷≠
# 1-modifiers start with an underscore and do not end with an underscore:
_mod←{𝔽𝕩}
# 2-modifiers must start and end with an underscore:
_mod2_←{𝔾𝕨𝔽𝕩}</syntaxhighlight>
=={{header|C}}==
Line 288 ⟶ 301:
;Libraries
Constants that appear in C "header" files are typically in upper-case: <
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 "__":
<
size_t __n, FILE *__restrict __s) __wur;</
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.
<
double cos(double x);
float cosf(float x);
long double cosl(long double x);</
Whereas for complex variable a prefix of "c" is added.
<
double complex ccos(double complex z);
float complex ccosf(float complex z);
long double complex ccosl(long double complex z);</
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:
<
int printf(const char *format, ...);
Line 321 ⟶ 334:
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);</
;Function names
Line 342 ⟶ 355:
'''Naming'''<br/>
- Names of enums should be plural if it's a flags enum, otherwise it should be singular.
<
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Line 358 ⟶ 371:
Workdays = Monday | Tuesday | Wednesday | Thursday | Friday
AllWeek = Sunday | Saturday | Workdays
}</
You should:<br/>
- prefix interface names with I e.g. IPrinter
- prefix generic type parameters with T e.g. <syntaxhighlight lang
most of the time, a single T is sufficient e.g. <syntaxhighlight lang
- 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 ⟶ 427:
* 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. <
(defvar *language* :en
"The language to use for messages (defaults to English)")
Line 449 ⟶ 462:
Hace demasiado frío en invierno
It's too cold in winter
</syntaxhighlight>
* 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 <
(defun do-something (argument &key ((secret-arg secret) "default"))
(format t "Argument is ~a, secret is ~a" argument secret))
Line 461 ⟶ 474:
;; Special caller:
(do-something "Foo" 'secret-arg "Bar")
</syntaxhighlight>
* 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 ⟶ 486:
** 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. <
#+sbcl
(defun user-name+home-phone (user-id)
Line 483 ⟶ 496:
(declare (ignore office office-phone _))
(values real-name home-phone)))
</syntaxhighlight>
* 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 ⟶ 516:
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>:
<
var ys = Array(1, 2, 3)
var str = xs.ToString()
type Maybe = Some(x) or None()
var x = Maybe.Some(42)</
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
// a module name is the name of the app or library, followed by the domain name of the organization;
// alternatively, a "throw-away" module can have a simple name, like "TestApp"
module shop.acme.com {
// other than modules, all type and class names (including enum values) use upper CamelCase;
const Point(Int x, Int y);
enum Color {Red, Green, Blue}
interface Callback {
// variables, properties, methods, and functions using lower camelCase
Boolean active;
void onEvent(String event);
void onError(Exception e);
}
// constants use upper CamelCase, or in some cases, UPPER_SNAKE_CASE
String DefaultLogin = "guest";
Int MAX_QUANTITY = 100;
// type variables are named for their meanings, and use upper CamelCase
interface Bag<Element>
extends Iterable<Element> {
void add(Element e);
}
}
</syntaxhighlight>
=={{header|Factor}}==
Line 649 ⟶ 689:
====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 ⟶ 705:
HR_RECORD 992 PERSONEL RECORD! \ store HR_RECORD
</syntaxhighlight>
====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 ⟶ 719:
m: clear 0 swap ! ;m
;class
</syntaxhighlight>
=={{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:<
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 ⟶ 739:
===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:
<
PRINT *,I
999 CONTINUE</
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
<syntaxhighlight lang
=={{header|Free Pascal}}==
Line 758 ⟶ 798:
Other conventions are also in use.
=={{header|Java}}==
According to Java's naming conventions, all names should be in mixed case:
classes and interfaces should be nouns beginning with a capital letter,
methods should be verbs beginning with a lower case letter,
variables should begin with a lower case letter.
Names should be descriptive, and single character names should be avoided except for short lived temporary variables.
Class variables which are static and final should be all upper case with words separated by underscores.
It is standard practice for an enum to be named in the same way as a class with its constants in all upper case.
The following program illustrates these naming conventions.
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.List;
public class NamingConventions {
public static void main(String[] arguments) {
SolarSystem solarSystem = new SolarSystem();
solarSystem.showSunDiameter();
System.out.println("The planetary system comprises of:");
solarSystem.listPlanets();
}
}
enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO }
class SolarSystem {
public SolarSystem() {
for ( Planet planet : Planet.values() ) {
planets.add(planet);
}
}
public void showSunDiameter() {
System.out.println("The diameter of the sun is approximately " + SOLAR_DIAMETER + " km");
}
public void listPlanets() {
System.out.println(planets);
}
private List<Planet> planets = new ArrayList<Planet>();
private static final int SOLAR_DIAMETER = 1_390_000;
}
</syntaxhighlight>
{{ out }}
<pre>
The diameter of the sun is approximately 1390000 km
The planetary system comprises of:
[MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO]
</pre>
=={{header|jq}}==
Line 800 ⟶ 902:
The following program illustrates these conventions:
<
const val SOLAR_DIAMETER = 864938
Line 830 ⟶ 932:
println("\nIts planetary system comprises : ")
ss.listPlanets()
}</
{{out}}
Line 841 ⟶ 943:
=={{header|Lambdatalk}}==
<
Naming conventions
Line 883 ⟶ 985:
- 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>
=={{header|Lua}}==
Line 894 ⟶ 996:
- Use _ for unneeded variables
- Don't use Hungarian Notation
<
local distance_to_target = 0
local function distanceToTarget() end
Line 901 ⟶ 1,003:
for _,v in ipairs(table) do
print(v)
end</
=={{header|M2000 Interpreter}}==
Line 918 ⟶ 1,020:
Groups which return strings also have to use $ in names, but these have two names as in this example:
<syntaxhighlight lang="m2000 interpreter">
Class Alfa$ {
Private:
Line 953 ⟶ 1,055:
Checkit &A$
Print A$
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Line 960 ⟶ 1,062:
Convention is that user variables and function names also also cammel case except they start with a lower case. eg myFunctionName. There is no limit to the number of characters in a user symbol, symbols can contain digits and non-ascii characters.
=={{header|MIPS Assembly}}==
* Registers typically start with a dollar sign, e.g. <code>$a0</code>, <code>$ra</code>, etc. Not all assemblers require this.
* Constants are usually in all capitals.
* Function names are often in CamelCase with the first letter being lowercase.
* <code>byte</code> is 8-bit, <code>halfword</code> is 16-bit, and <code>word</code> is 32-bit. However, it is up to the programmer to correctly use the data. The CPU never sees these declarations once the program is assembled, so there's nothing stopping you from loading data at the "wrong" length.
=={{header|Nim}}==
Line 966 ⟶ 1,074:
:- 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.
<
const aConstant = 42
const FooBar = 4.2
Line 974 ⟶ 1,082:
# Types must start with an uppercase letter.
type
FooBar = object</
:- 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 982 ⟶ 1,090:
:- Unless marked with the {.pure.} pragma, members of enums should have an identifying prefix, such as an abbreviation of the enum's name.
<
PathComponent = enum
pcDir
pcLinkToDir
pcFile
pcLinkToFile</
:- Non-pure enum values should use camelCase whereas pure enum values should use PascalCase.
<
PathComponent {.pure.} = enum
Dir
LinkToDir
File
LinkToFile</
=={{header|OASYS Assembler}}==
Line 1,088 ⟶ 1,196:
.eu - linux-only include<br>
.exw - historically this implied windows-only, but is now also used for any cross-platform gui applications.<br>
=={{header|Phixmonti}}==
No naming conventions. All is only words, numbers, lists or strings (delimited by double quotation marks) separated by blanks. Caution! redefine words is not reversible.
<syntaxhighlight lang="Phixmonti">def *'#-? "Hello world" print enddef
*'#-? nl
10 var +{&
+{& print
5 var + /# redefine + to variable with value 5. Aritchmetic word is missing #/
+ print</syntaxhighlight>
{{out}}
<pre>Hello world
10
5
=== Press any key to exit ===</pre>
=={{header|PicoLisp}}==
Line 1,138 ⟶ 1,264:
The convention is to use full English lowercase words separated by dashes
<
render-game-state
send-message-to-client
traverse-forest</
Usually <code>_</code> is used only as the name of a dummy argument.
Line 1,147 ⟶ 1,273:
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.
<
(string-ref "1234" 2)
(string-length "123")
Line 1,153 ⟶ 1,279:
;exceptions:
(append (list 1 2) (list 3 4))
(unbox (box 7))</
This convention generalizes the selector-style naming scheme of <code>struct</code>s.
<
(struct pair (x y) #:transparent #:mutable)
(define p (pair 1 2))
Line 1,163 ⟶ 1,289:
(set-pair-y! p 3)
p ; ==> (pair 1 3)
</syntaxhighlight>
The name of conversion procedure is usually like <code>from->to</code>
<
(list->vector '(1 2 3 4))
(number->string 7)</
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">
;predicates and boolean-valued functions: ?
(boolean? 5)
Line 1,187 ⟶ 1,313:
;interfaces: <%>;
dc<%>;
font-name-directory<%></
=={{header|Raku}}==
Line 1,263 ⟶ 1,389:
For example:
<
─── where '''length''' is a REXX BIF for the ''length'' of the value of the variable '''ABC'''
If there is an internal function with a built-in function's name in the program, the built-in (REXX)
<br>function can be invoked using its name as an uppercase literal string as shown below:
<
say "length(s) =" length(s) /* ──► 1000 */
say "'LENGTH'(s) =" 'LENGTH'(s) /* ──► 4 */
exit
length: return 1000</
{{out|output}}
<pre>
Line 1,312 ⟶ 1,438:
===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">
test_variable = [1, 9, 8, 3]
test_variable.sort # => [1, 3, 8, 9]
Line 1,318 ⟶ 1,444:
test_variable.sort! # => [1, 3, 8, 9]
test_variable # => [1, 3, 8, 9]
</syntaxhighlight>
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,327 ⟶ 1,453:
Here is an example of a ruby file with proper naming conventions being used.
<syntaxhighlight lang="ruby">
# Global variable
$number_of_continents = 7
Line 1,375 ⟶ 1,501:
end
end
</syntaxhighlight>
=={{header|Rust}}==
Line 1,419 ⟶ 1,545:
'''Camel case:'''<br>
The variable name begins with a prefix and has one or more uppercase inside.
<syntaxhighlight lang
'''Hungarian notation:'''
<
Dim sName as String
Dim nPopulation as Long
Dim xLightYear as Double
iRow = iRow + 1</
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,467 ⟶ 1,593:
|}
Exemple:
<
cmdSolution.Enabled = False
mnuAleatoire.Checked = False
frmScore.Show vbModal
picFace.Visible = False
picFace.Picture = LoadPicture(sFileName)</
The advantage comes clear for the “Private Sub” names of the controls:
<
cmdSolution_Click()
frmScore_Resize()</
=={{header|Wren}}==
Line 1,558 ⟶ 1,684:
;Examples:
<syntaxhighlight lang="zig">
const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
Line 1,602 ⟶ 1,728:
// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}
</syntaxhighlight>
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.
|