Bugged by Bugs? Master Debugging!

Bugged by Bugs? Master Debugging!

Last Updated on May 2, 2021 by Rakesh Gupta

Debugging is an art of finding errors. There are certain constants in life which are unavoidable – death, taxes, and bugs in programming! Debugging comprises of finding the source of a problem in a code base, identifying possible causes, testing out hypotheses until the ultimate cause is found, and then eventually eliminating that cause and ensuring that it will never happen again.

Before we take a deep dive into mastering debugging, let me draw your attention to my previous article Pre-requisites for Learning Apex – Logical Mind and Confidence! I discussed Variables naming convention and Operators. There were few assignments for you in that article, if you did not get a chance to complete it, do it right now. It will not take more than 30 minutes to complete them. 

Irrespective of whether you are a newbie, just starting a career as a Salesforce Developer, or have some programming background, I would suggest you complete the assignments. The assignments will help you to, either learn few new things or, at the least, brush up your concepts.

This is the third article in learning Apex series. If you have not read first two articles – Mastering Apex Variables – a Stepping Stone in your Apex Journey and Pre-requisites for Learning Apex – Logical Mind and Confidence! – I strongly recommend going through it now. At bare minimum, these articles will help you to brush up your basic concepts of programming. 

The common question people repeatedly ask me is – Are there any prerequisites to start learning Apex Programming? To that, my simple answer is – yes!  However, my recommended prerequisites is not to practice ABCs of Apex! But, it is to cultivate your ability to build logic! If you cultivate your logical mind then, it is not difficult to learn programming languages. After all programming languages are created by mortals like us!

A person who really wants something will find a way, a person who does not will find an excuse. 

To learn Apex programming, remove the rust! One of the most efficient ways to do so is to complete a Sudoku puzzle daily – start with easy puzzles.  Let this be a starting point, or a pre-requisite, of your Salesforce Developer Journey!

Second suggestion – start writing Pseudocode instead of writing Apex code directly. It means solving the problem in plain English (Pseudocode)! And, only then, write the code. Pseudocode is an easy way of writing programming code in English – it is not an actual programming language. It uses short phrases to spell out the logic on how one would solve a requirement before one creates codes in a particular language. Once you are confident about Pseudocode, only then start converting your Pseudocode into any programming language – in our case, into Apex. Remember Pseudocode is just plain English not related to any programming language. 

Salesforce offers lots of content to get you started on your Apex journey. If you are just starting your Salesforce Developer career then read this article – Creatively Decode Your Salesforce Developer Journey– to get some guidance, as well as, to learn how to achieve your Salesforce Developer goal. 

My primary purpose, through this and other blogs, is to be your guide and a mentor. As for Apex learning tools – such as browsing through Apex content to get you started on learning the language – there is no shortage of material available on the Web. For example, search for ‘best practice to write Apex trigger’ and you will end up with hundreds of article links. If, however, you fail to start your journey with a right mindset, it is unlikely that you will go far by practicing the codes and triggers mindlessly. So, let us start your Apex journey strategically.

Debugging is not limited to Programming – It is Omnipresent!

Let us start with a real world scenario – when you or your family member has health issues, the first thing you do is consult a doctor. Now, the doctor is not omniscient – he/she can not identify the problem just by looking at the patient. To determine the problem, the doctor will ask you to do few tests and these tests will help him/her determine the cause (diseases).

Similarly, let us look at one more example. Let us say your iPhone is not working. If so then, you, will most likely, visit a near by Apple store to get it fixed – is it not? An Apple technician is not pansophical – he/she can not look at your phone and determine the problem. To find the actual problem, he/she may either take few minutes, or an hour or two, to examine your phone. 

The world of programming is no different!  Bugs occur in programs when a line of code, or an instruction, conflicts with other elements of the code.

The mindset and attitude towards debugging is perhaps the most important part of mastering programming skills. This is because, it determines how efficiently you will fix the error, and what you will learn from it — if anything. If you connect things with real life then it is not hard to learn new stuff. 

Every error is an opportunity to learn, almost always about yourself

So whenever you encounter a bug, welcome it with open arms! Treat it as a mystery! Gamify it! Think about how much fun you are about to embark on to crack the bughole! Although you will have lots of fun cracking the mystery, there is a method to this madness. To succeed, you must crack the bug systematically. Do so by taking a paper and pen and jotting down your assumptions. Then, test our assumptions – one-by-one if need be, and, by using every tool at your disposal, especially debug Log. Then after the mystery is solved, you can do even better by looking through all your code for similar errors that you may have made; and write unit test classes to ensure the error will not happen, unknowingly, again.

Since so much of your time will be spent debugging codes, it is probably a good idea to master the art of debugging – do you agree?

We can mainly use the following tools for debugging: 

  • Developer Console
  • Debug Log

A debug log can records database operations, system processes, and errors messages that occur when executing a transaction or running unit tests. It is very useful for debugging the program. In this article, however, I am going to focus on how to debug Apex code through Developer Console. 

Debugging through Developer Console

The Developer Console is a great tool for debugging. You do the following things and much more with the developer console. 

  • View Logs:- Another way to view debug output other than the Debug Log. 
  • Execute SOQL:- You can write simple SOQL query here to find the correct record sets. 
  • Execute Anonymous: – You can run Apex code directly from the developer console. It executes code as the current user context and can fail to compile if the code violates the user’s object- and field-level permissions.
  • Set and View Checkpoints in Apex Code: – Checkpoints are used to evaluate the values of variables at points of execution in your code. 
  • Source Code Editor: – It allows you to create, edit or modify  Apex Class, Apex Trigger, Lightning Component, Visualforce page. 

One last thing to understand – system.debug(). Let us take real world example. While driving, you may have seen many signs on the road to help drivers – like signal, speed limit, milestone or route direction. These are guides to help us to reach our destination safely. 

Similarly in Apex, system.debug() is our friend; it helps us to understand the program and at the same time it also helps us to understand what actually is happening with the code. Basically, it is your guide to debug Apex code. Similar to Java System.out.println,  System.debug (‘my name is Rakesh Gupta’) simply prints the value of anything you put inside it. Remember to use single quote (‘) not double quote (“). 

Now look at these examples,

  System.debug('I love Trailhead'); //simply print "I love Trailhead "

  Integer badgesThisMonth = 20; //Trailhead badges earned in the current month
  Integer badgesLastMonth = 40; //Trailhead badges earned in the last month
  Integer totalBadges = badgesThisMonth+ badgesLastMonth; // Total Trailhead badges earned

  System.debug(totalBadges); //It will print number 60. 

In the above example, System is a system class and debug() is a system method.

To check the output of your System.debug(), you need to open developer console and run the preceding code in Execute Anonymous, as shown in the following screenshot: 

Once you are done with reviewing the answer,  click on the Execute (2) button. Make sure to select Open Log (1) check box. Once you do that, the log will automatically open in the Log Inspector after the code executes. 

To better analyze the system.debug statements, make sure to select the Debug Only check box, as shown in the following screenshot:

Now onwards use the system.debug() statements in your code to identify where it is breaking. You can also use it to track the value of a variable at any given point of time in programming execution. 

That is it for today’s blog. In the next article, I am going to discuss Comments – why are they useful? in programming.  

Technical Editor and Proofreader: - Munira Majmundar

Good News: – What an amazing moment! I was just notified that my MVP title has been renewed for the 4th time. I am truly awed and humbled to know that my work has been appreciated and recognized by one of the most innovative company in the world – Salesforce! Please check it out here – https://www.salesforce.com/blog/2017/09/welcome-28-new-salesforce-mvps.html

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

4 thoughts on “Bugged by Bugs? Master Debugging!

  1. Rakesh,

    Another great article. Since we’re talking about Apex debugging, one recommendation is to write one or more unit tests to confirm that the bug is fixed and stays fixed. If possible, write the failing unit tests first and then when they pass, you know they’re fixed. I’ve seen people forget this step and then the bug appears again in a future release.

    Also, congrats on becoming an MVP again! Don’t forget to update your bio at the bottom of the page to say 4x Salesforce MVP.

    1. Thanks for your kind words, Luke! I have updated my profile.

      Great suggestion about writing unit test cases for positive and negative scenarios.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.