October 8, 2016 by LanceShi
2.6 Variable naming conventions
In our previous posts, we mentioned that you can pretty much name your variable anything you want. But it doesn’t mean you should give them just random names. For Apex compiler, it really doesn’t make any difference. But remember, our programme is written for human to read, not for compilers.
So the following code:
Decimal personalIncome = 5000; String firstName = 'Lance'; Boolean isWorkingDay = true;
Decimal a = 5000; String b = 'Lance'; Boolean c = true;
are the same from a compiler’s point of view. However, you should definitely follow the first code sample’s naming conventions to make your variable names meaningful.
Imagine you are explaining to your support team:
“I am trying to insert a record into p and z is giving me a validation error. I tried to update a but c would not let me. Do i need to update y first, not sure cause I know the aa is set properly.”
I can almost hear the crying from the support team. It is the same thing for variable name. You should make the variable names make sense so that it will save so much time and effort in the future to look into and understand this code.
Common Variable Name Conventions
Your variable name conventions is usually pre-defined in the dev team. It doesn’t always need to be the same. As long as it consistent and make sense, it should be fine. As we are learning, I am going to introduce the general naming conventions for Java, as currently we don’t have on for Apex yet:
|Identifier type||Rules for naming||Examples|
|Classes||Class names should be nouns in
|Methods||Methods should be verbs in
|Variables||Local variables, instance variables, and class variables are also written in
|Constants||Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character.||
This table is copied from wikipedia.
As we are introducing Apex in our course and some variables don’t have much actual usage, I will still use some simplified variable names like s or d in the future. But make sure you use the proper variable name if you are programming something meaningful.