Last Updated on April 15, 2019 by Rakesh Gupta
I am touched, and humbled, to receive hundreds of emails thanking me for writing the following blogs – ‘An Unconventional Path to Getting Salesforce Administrator Certification’ and, ‘Creatively Decode your Salesforce Developer Journey’. Thank you!
Many of you ask, and wonder, why I spend so much time writing blogs. The simple answer is, I enjoy it. Teaching – imparting one’s knowledge – is an art of heart. I am grateful to have been bestowed with the ability, and desire, to teach. I am filled with joy when my insights help others. So, thanks to all of you for your feedbacks. I am happy to know that my contributions are helping you to achieve your targeted goals.
One of the reasons why my writings resonate with many of you is that I write directly from my experiences. I take the time to jot down my thoughts on paper; then, I revise, and re-revise, my drafts until I can answer ‘Yes’ to the following question – is this worth sharing with the community? If the answer is ‘Yes’, I publish the blog; if, however, the answer is ‘No’ then I go back to the drawing board and restart the cycle. I continue the exercise until I am satisfied with the output beyond any shred of doubt.
Morals of the story:
- Never give up
- Refine relentlessly until you are satisfied with the output
Many of you email me wondering why, even after following instructions laid out in my blog, or taking few courses on Apex, you are still not comfortable working with Apex? The reason(s) is, none of the courses, blogs, books or training, will help you become masters in your life or in any technology. Books, blogs, courses are mere mediums to guide you. These tools, by itself, will not be enough to achieve your goal. Let me start with an example. Let us say you want to learn swimming. So, with lots of enthusiasm, you sign up for a swim class. Does that mean you will learn swimming? Probably, yes. Probably, no. Swimming class is a mere medium for you to learn swimming – now, whether you will learn or not will depend on your efforts, quality of your coach, and several other factors.
The same logic applies in the world of programming. As mentioned, none of the courses, or training, will help you to become a good programmer until and unless you – persistently and diligently – work at, and towards, it on regular basis. Most people leave the world of programming – frustrated and depressed – because they do not see fruits of their hard work soon enough. To reverse this trend, the first thing a budding programmer should do is to change his/her attitude and expectations. Begin by trusting yourself – yes, you can do it too. Apex programming is not a black box; many have learnt before you and many will do so after you! In short, it is not a rocket science.
To remove flickers of your doubts – if there are any left even after reading the above paragraphs – let me share with you my experiences when I was attempting to learn Flows. Yes, now I am perceived as one of the seasoned automation champions; but like all masters before me, I too was one of the struggling, budding, students of Flow. Unlike today, when I started learning Flows, there were hardly any blogs or articles about it. It was very hard for me to learn and create solutions using Flows. But I was determined to master Flows. I disregarded frustrations and transcended them. I started exploring any, and all, available resources; spent many hours doing so; and, finally, developed semi-decent Flows at first. Then, I continued to refine my Flows until I was satisfied with the output. There were times when I spent weeks to find one simple solution. At other times, after struggling for hours on a problem, I would realize that using Flow was not the best tool to solve a given problem. Even at such times, and, in fact, because of such experiences, I sharpened my understanding of the capabilities of Flows and its limitations!
In all, and any, case(s), one thing remained constant – I always maintained a positive attitude and believed that, sooner or later, either I will find the solution I am looking for; or, I will find something better!
The aforementioned groundwork is a good diving board from which to dive into your Apex journey. So, shall we start? Begin our journey to learn the role of Variable in Apex programming? Great! Let us begin by asking a simple question – What is a Variable?; What role does a Variable play in Apex?
Variable is a container that stores information. Let us take a real life example. Suppose if someone requests you to store two pounds of rice. The first thing you will do is to look for a container to store the rice. Similarly, if you are traveling, and want to carry some frozen food, you will look for a specially designed bag/container to carry frozen food.
Notice that, in the above example, a container needed to store rice is different than a container needed to store frozen food. So, different containers are needed to store different types of items – A Ziplock bag may not be as desirable a container to store liquid – milk or juice – as a glass or a plastic bottle/box. Variables in Apex are no different; in the programming language too we have different types of variables to store different types of data. We call it – Data types. If a variable stores text, it will need a String Data Type; if it stores numbers, it will need an Integer Data Type. Therefore, before storing any data into a variable you must define its type. Here is the list of Data Types in Apex programming language. Data types in the programming language are divided into two types:
- Primitives are the basics building blocks that are built into a language and can not be broken down. For example, String, Date, etc.
- Composites are the non-primitive data types that are built from other data types. It is also possible to create your own data types by extending the language.
Now some hands-on – let us create few variables:
String favPhrase = ‘I love Trailhead'; //favPhrase is a string used to store characters surrounded by single quotes. Integer noOfTrailheadbadges = 100; //noOfTrailheadbadges is a natural number that does not contain a decimal point. Decimal mySalary = 1087.76; //mySalary is number is a real number that contains a decimal point. Boolean areYouTrailblazer = true; //areYouTrailblazeris a Boolean variable that use to store true, false, or null. Date TodayDate = Date.today(); //TodayDate is a date variable used to store today’s date. Datetime CurrentDateTime = Datetime.now(); //CurrentDateTime is a datetime variable used to store current date time.
—> To create a single line comment, use //. All characters on the same line to the right of the // are ignored by the compiler.
—> To create a multi line comment, use /* and */ to demarcate the beginning and end of the comment block.
Codes are ignored the compiler.
Codes are ignored the compiler.
Codes are ignored the compiler.
—> favPhrase is a text variable which holds the information of characters ‘I love Trailhead’. Strings are surrounded by two single quotes(‘) in Apex.
—> noOfTrailheadbadges is an Integer variable, means a natural number variable. It can be both positive and negative.Integers have a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647.
—> Decimal and Double are both real numbers. They both can use to store numbers with decimal points. The difference is Decimal is a flexible precision and Double is fixed precision, which impacts how much space it would be using.
—> A Boolean variable only holds two values – true or false. It can also be null, like any variable else, which means no value, if nothing is defined.
—> Date and DateTime variables use to store Date and DateTime respectively
The next step is to create these variables and display their value. For this, we will use Developer console. Before moving ahead, I suggest you complete Developer Console Basics Trailhead module. It will give you a basic idea about Developer Console and how to use it. I am using Salesforce Lightning Experience in this demo but, you can use Salesforce Classic interface as it will not impact anything expect the path to access Developer Console. To access Developer Console, follow the instructions below:
- Login into your developer org.
- Click on Setup (Gear icon) | Developer Console.
- I will be using Execute Anonymous Apex tool in the Developer Console to run the Apex code. An anonymous block is an Apex code that does not get stored in the metadata but, can be compiled and executed. Anonymous blocks execute as the current user and can fail to compile if the code violates the user’s object – and field-level – permissions.
- To open Execute Anonymous window, click on Debug | Open Execute Anonymus Window. If you want to use the keyboard shortcut, press Control+E, as shown in the following screenshot:
- It will open execute anonymous window where you have to paste the code, as shown in the following screenshot:
- To execute all codes in the window, click on the Execute button. Make sure to select Open Log check box. Once you do that, the log will automatically open in the Log Inspector after the code executes.
- The debug log will be listed on the Logs tab. Double-click the log to open it in the Log Inspector. In our case, the log will automatically open after the code executes. To better analyze the variables’ run time value, make sure to select the Executable check box, as shown in the following screenshot:
- The preceding screenshot displays the runtime value of variables. For example, you can check the variables TodaysDate or CurrentDateTime values. As we are using the formula for it, values will be different based on your code execution time.
That is it for today’s blog. In the next article, I am going to discuss arithmetic operations and significance of system.debug.
- Create a variable that stores the current year. Do not hardcode current year; instead, use formula.
- Create variables to store logged-in user name, Locale, preferred User Interface (Classic or Lightning Experience). Do not hardcode values; instead, consider using UserInfo class.
- Create a variable to store the length of logged-in username. Consider using String class.
- Create a variable that will store first 5 characters of logged-in user’s last name. Consider using String class.
- Create a variable that will store Start Date of the current week. Consider using Date class.
Note: – I am thankful to Smartcloud.io for sponsoring my blog.
Technical Editor and Proofreader: - Munira Majmundar
Please feel free to share it with your family, friends, and colleagues!