Day 4: What are the best Practices for variable naming?

Variables are so important to the code that they deserve a good name that accurately describes their purpose. Sometimes a bad name can be the difference between a fellow developer understanding what everything does at first glance and not having any clue where to begin.

Today, the challenge is to share one essential thing to consider when variable naming. You should nominate another one after posting yours.

I’ll start with a simple one.

Naming booleans

Booleans can hold only 2 values, true or false. Given this, using prefixes like “is”, “has”, and “can” will help the reader infer the type of the variable.

// bad
const open = true;
const write = true;
const fruit = true;
// good
const isOpen = true;
const canWrite = true;
const hasFruit = true;

I nominate @Gravewalker :blush:

2 Likes

Meaningful Variable Names
Always give your variables meaningful names, defining what goes in the variable. Avoid using generic names like ‘x’, ‘a’, etc.

// bad
String a = "Heshan";
int x = 2;
// good
String firstName = "Heshan";
int nameCount = 2;

I nominate @janithRS to continue.

1 Like

Obey programming language standards and don’t use lowercase/uppercase characters inconsistently

For example in Java

  • use Camel Case (aka Upper Camel Case) for classes: VelocityResponseWriter
  • use Lower Case for packages: com.company.project.ui
  • use Mixed Case (aka Lower Camel Case) for variables: studentName
  • use Upper Case for constants : MAX_PARAMETER_COUNT = 100
  • use Camel Case for enum class names and Upper Case for enum values.
  • don’t use ‘_’ anywhere except constants and enum values (which are constants).

Nominate @piumal1999 to continue

1 Like

Don’t use too long variable names

Long names will bring ugly and hard-to-read code, also may not run on some compilers because of character limit. So use short enough and long enough variable names in each scope of code. Generally length may be 1 char for loop counters, 1 word for condition/loop variables, 1-2 words for methods, 2-3 words for classes, 3-4 words for globals.

I nominate @osusara😁

1 Like

Don’t reuse the same variable name in the same class in different contexts

As an example in a method, constructor, class. So you can provide more simplicity for understandability and maintainability.

I nominate @anjisvj :grin:

1 Like