Naming variables in Kotlin

Why naming is important?

  • Every variable should have a unique name that identifies it.
  • Always give descriptive and concise names to all variables.
  • There are two sets of rules that restrict possible names for variables.
  • Naming Rules
    • Names are case-sensitive (number is not the same as Number).
    • Each name can include only letters, digits, and underscores.
    • A name cannot start with a digit.
    • A name cannot be a keyword (for example val, var, fun are illegal)
    • No whitespaces are allowed in a variable's name.
    • Note: If you break these rules, your program will not work.
  • Conventions for naming variables
    • If a variable name is a single word, put it in lowercase (for example - number, value)
    • If a variable name includes, multiple words, put them in lowerCamelCase, so that the first word is lowercase, while other words start with a capital letter (for example - numberOfCoins)
    • Do not start variables with an underscore _. Technically, you can do it, though.
    • Choose meaningful names for your variables, for example, score makes more sense than s, although they are both valid.
  • Magic Numbers
    • Constant values must be stores in immutable variables, namely constants.
    • Constant means we are not talking about just any values declared as val. By constants we mean values which we denote as const val outside of the main() function or any other function. These are completely immutable constants.
    • The name of a constant should be meaningful, and when naming constants, we use the UPPER_SNAKE_CASE style.

Do's and Don'ts 

  • The name of a constant should be meaningful, and when naming constants, we use the UPPER_SNAKE_CASE style.


Comments