1.3 Comments – why are they useful?

The concept

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');

and


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:

  1. Single line version. Use // and all the following line are considered as comments.
  2. 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.

Next Post

2.1 Using variables to store information

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

#Apex#Tutorial

Leave a Reply

Your email address will not be published / Required fields are marked *