September 24, 2016 by LanceShi
1.3 Comments – why are they useful?
In short, comments are something which is for human to understand the piece of code, but doesn’t make any actual different to computer. Compilers will automatically ignore all the comments you have written in your code. So:
//Display Hello World in the debug log section System.debug('Hello World');
has absolutely no difference from compilers point of view.
So, why do we need to have comments?
The reason is simple, but the concept should be well understood by every new developer. Programmes must be written for people to read, not for computers. This is a famous quote by Harold Abelson:
“Programs must be written for people to read, and only incidentally for machines to execute.”
Please understand and remember this sentence by heart. This is the No. 1 rule if you want to be a good developer.
Grammar and a bit explanation
There are two ways to write comments in Apex:
- Single line version. Use // and all the following line are considered as comments.
- Multi line comments. Multi line comments start with /* and end with */
Below is an example:
/* This is a multi-line comment. This code is written by Lance Shi on Sept 24, 2016 to introduce the usage of comment. */ //This is single line comment //Display Hello World in the debug log section System.debug('Hello World');
The grammar is pretty simple.
You don’t need to explain everything in the code. Everyone with proper Apex coding knowledge would be able to understand what System.debug(‘Hello World’) means. However, if you have written some one-hundred-line complicated code, it will be a good idea for you to leave some comment explaining what was happening here. Please keep that in mind.