Variable Naming
This document provides details on how to best name variables. The guidance provided here is mandatory when using TypeScript.
Rationale
Having clear variable names make the code more readable and more maintainable. Understanding the mutability of variables and reducing it to have fewer side effects results in more robust code. The rules on this document were discussed as a team and are quite standard across TypeScript projects.
Description
When naming variables, consider the following rules:
- Use
lowerCamelCase
for variable / parameter / function / method / property / module alias. - Use
UpperCamelCase
for class / interface / type / enum / decorator / type parameters. - Use
CAPITALIZED_SNAKE_CASE
for environment variables/global constant values. - Keep variable names declarative.
- Use the
is<Status>
format for boolean variables, and keep the<Status>
positive. - Shorter names are better than longer names. However, readability is more important than terse code.
- Avoid abbreviated variable names except for the following accepted conventions:
e
for event,err
for error andi
for index.- Additionally, industry wide acronyms (e.g.
url
,db
,dns
) or CRUK-specific products (e.g.ews
,fws
) are acceptable - though, if in doubt, spell it out.
- Additionally, industry wide acronyms (e.g.
In general, for variables use const
and let
and never use var
. This is covered as part of our style guidelines. Additionally, let
is likely a code smell and should be avoided by writing the code to be more functional with few or no side effects.
Examples
Names that follow the convention: ✔️
databaseError: Error
databaseErrorMessage: string
isValidRequest: boolean
getError: () => Error
getErrors: () => Error[]
handleChange: React.ChangeEvent<HTMLInputElement>
isEnabled: () => boolean
err: Error
emailAddress: string
paymentURL: string
PAYMENTS_SQS_ARN: string
(for an environment variable)DatabaseAdapter
(for a class)
Names that do not follow the convention: ❌
xx
: abbreviated and not declarative.db-error
: abbreviated and not camel case.tmpVar2
: not declarative.isFalse: boolean
: avoid negative variable boolean names.frontendReactComponentForTogglingAddressFieldOnOrOff
: Too verbose. ConsideraddressFieldToggle
oraddressFieldToggleComponent
.
References & Further Reading
- Google's TypeScript style guide (https://google.github.io/styleguide/tsguide.html#naming)
- Tips on naming boolean variables (https://michaelzanggl.com/articles/tips-on-naming-boolean-variables/)
- MakeCode naming conventions (https://makecode.com/extensions/naming-conventions)