Skip to main content

Variable Naming

This document provides details on how to best name variables.

info

This content 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:

  1. Use lowerCamelCase for variable / parameter / function / method / property / module alias.
  2. Use UpperCamelCase for class / interface / type / enum / decorator / type parameters.
  3. Use CAPITALIZED_SNAKE_CASE for environment variables/global constant values.
  4. Keep variable names declarative.
  5. Use the is<Status> format for boolean variables, and keep the <Status> positive.
  6. Shorter names are better than longer names. However, readability is more important than terse code.
  7. Avoid abbreviated variable names except for the following accepted conventions: e for event, err for error and i 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.

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. Consider addressFieldToggle or addressFieldToggleComponent.

References & Further Reading